我正在尝试从JSON文件中获取数据jquery ui autocomplete不起作用。这是我的JSON数组
[
{
"FIELD1": "A",
"FIELD2": "B",
"FIELD3": "C"
},
{
"FIELD1": "ITEM ",
"FIELD2": "RATE LIST",
"FIELD3": "HSN Code"
},
{
"FIELD1": "HORSES - PURE-BRED BREEDING ANIMALS ",
"FIELD2": "0.12",
"FIELD3": "1011010"
},
{
"FIELD1": "ASSES - PURE-BRED BREEDING ANIMALS ",
"FIELD2": "0",
"FIELD3": "1011020"
}]
我试图在jquery ui自动完成中获取这些结果,但它无法正常工作
$( function() {
$('#tags').autocomplete({
source: function (request, response) {
$.getJSON("check.json?term=" + request.term, function (data) {
response($.map(data.dealers, function (value, key) {
return {
label: value,
value: key
};
}));
});
},
minLength: 2,
delay: 100
});
} );
答案 0 :(得分:0)
由于您无法更改JSON文件,我建议:
source: function (request, response) {
$.getJSON("check.json", function (data) {
var results = [];
console.log("Data:", data);
$.each(data, function(k, v){
console.log("Checking if", request.term, "is part of", v.FIELD1);
if(v.FIELD1.indexOf(request.term) == 0){
console.log("True");
results.push({
label: v.FIELD1,
value: v.FIELD2,
hsn: v.FIELD3,
oData: v
});
} else {
console.log("False");
}
});
console.log("Sending results:", results);
response(results);
});
}
这将引入所有结果,因为它是JSON而不是服务器端脚本文件。然后,您需要查找请求期限。这是$.each()
有用的地方。您也可以使用$.ui.autocomplete.filter()
。对于这种情况,它不那么有用,因为它需要一个数组和术语来过滤。
<强>更新强>
在我看到你的小提琴后,我把它分成了一个工作的例子:
https://jsfiddle.net/Twisty/uejaafuk/
<强>的JavaScript 强>
var myData = [{
"FIELD1": "A",
"FIELD2": "B",
"FIELD3": "C"
}, {
"FIELD1": "ITEM ",
"FIELD2": "RATE LIST",
"FIELD3": "HSN Code"
}, {
"FIELD1": "HORSES - PURE-BRED BREEDING ANIMALS ",
"FIELD2": "0.12",
"FIELD3": "1011010"
}, {
"FIELD1": "ASSES - PURE-BRED BREEDING ANIMALS ",
"FIELD2": "0",
"FIELD3": "1011020"
}];
$(function() {
$('#tags').autocomplete({
source: function(request, response) {
//$.getJSON("check.json", function(data) {
$.ajax({
type: "POST",
dataType: "JSON",
data: {
json: JSON.stringify(myData)
},
url: "/echo/json/",
success: function(data) {
var results = [];
console.log("Data:", data);
$.each(data, function(k, v) {
console.log("Checking if", request.term, "is part of", v.FIELD1);
if (v.FIELD1.toLowerCase().indexOf(request.term.toLowerCase()) == 0) {
console.log("True");
results.push({
label: v.FIELD1,
value: v.FIELD2,
hsn: v.FIELD3,
oData: v
});
} else {
console.log("False");
}
});
console.log("Sending results:", results);
response(results);
}
});
},
minLength: 2,
delay: 100
});
});