我在成功解析 JSON 文件以在 JQuery UI 自动完成中使用时遇到很大困难
请参阅我的开发页面:http://www.zyredesign.com/autocomplete
JSON 的组织方式并不像我希望的那样,因为项目键是 ID,例如:
{"140":"阿巴斯", "375":"讴歌" }
等等......
这是我的 JavaScript 尝试:
$(document).ready(function() {
$('#cars').autocomplete({
source: function()
{
$.getJSON('json.json', function(data)
{
cars_array = new Array();
$.each(data, function(k, v) {
cars_array.push(v);
})
alert( cars_array);
return cars_array;
})
},
minLength: 3,
focus: function( event, ui ) {},
select: function( event, ui ) {
$('#suggestions').html(ui);
return false;
}
});
});
/*
function get_json()
{
var items = new Array();
$.getJSON('json.json', function(data) {
var items = [];
alert( eval ("(" + data + ")") );
// $.each(data, function(key, val) {
//items.push('<li id="' + key + '">' + val + '</li>');
// });
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
return items;
}
*/
任何帮助将不胜感激,谢谢!
最佳答案
您为 source: 属性提供的函数不返回值。 $.get() 函数可以,但不会到达源属性。
source: function()
{
$.getJSON('json.json', function(data)
{
cars_array = new Array();
$.each(data, function(k, v) {
cars_array.push(v);
})
return cars_array;
})
//You need to return something here
}
此外,您以同步模式使用异步调用 json 文件可能会出现问题。换句话说,考虑一下:
$.getJSON('json.json', function(data)
{
cars_array = new Array();
$.each(data, function(k, v) {
cars_array.push(v);
})
//Now you definitely have the cars so you can do the autocomplete
$('#cars').autocomplete({
source:cars_array,
minLength: 3,
focus: function( event, ui ) {},
select: function( event, ui ) {
$('#suggestions').html(ui);
return false;
}
});
关于javascript - Jquery UI 自动完成 JSON 文件的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10824943/