jQuery Select2 从文件中使用 Ajax 加载数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18490609/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Select2 load data with Ajax from file
提问by user2725585
I have a script called listofValues.php
, which queries a database and returns JSON format values.
我有一个名为 的脚本listofValues.php
,它查询数据库并返回 JSON 格式值。
What I need is to pass these values to the select2
data
member. I need it to load once.
我需要的是将这些值传递给select2
data
成员。我需要它加载一次。
I don't need to pass values from select2
input (term) to my listofValues.php
as described in this example
我不需要将值从select2
输入(术语)传递给我listofValues.php
,如本例中所述
$('#select2div').select2({
//data:[],
ajax: {
dataType: "json",
url: "listofvalues.php",
success: function (data) {
}
}
Can you help me with this?
你能帮我解决这个问题吗?
回答by Simon Adcock
Simple Example
简单示例
It would be useful to know the format of the object you're getting back from listofvalues.php
, but let's just assume, for the sake of simplicity it looks like this:
了解您从中返回的对象的格式会很有用listofvalues.php
,但为了简单起见,让我们假设它看起来像这样:
[ {"id": 1, "text": "option1"},
{"id": 2, "text": "option2"},
{"id": 3, "text": "option3"} ]
This is the easiest format to use, as by default, select2
can handle objects with property names id
and text
and render them into a dropdown list. So your select2
initialisation might look like this:
这是最容易使用的格式,因为默认情况下,select2
可以处理属性名称的对象id
,并text
与他们呈现到一个下拉列表。所以你的select2
初始化可能是这样的:
$('#select2div').select2({
ajax: {
dataType: "json",
url: "listofvalues.php",
results: function (data) {
return {results: data};
}
}
});
Slightly Trickier Example
稍微棘手的例子
Now let's assume the data from listofvalues.php
doesn't follow the convenient naming conventions:
现在让我们假设数据listofvalues.php
不遵循方便的命名约定:
[ {"id": 1, "firstName": "John", "lastName": "Lennon"},
{"id": 2, "firstName": "Paul", "lastName": "McCartney"},
{"id": 3, "firstName": "George", "lastName": "Harrison"},
{"id": 4, "firstName": "Ringo", "lastName": "Starr"} ]
We'll have to set up a function to handle the output:
我们必须设置一个函数来处理输出:
function formatValues(data) {
return data.firstName + ' ' + data.lastName;
}
And our select2
initialisation:
还有我们的select2
初始化:
$('#select2div').select2({
ajax: {
dataType: "json",
url: "listofvalues.php",
results: function (data) {
return {results: data};
}
},
formatResult: formatValues
});
Let me know how you get on.
让我知道你是怎么办的。