gpt4 book ai didi

javascript - 选择 2 并加载 JSON 数据

转载 作者:行者123 更新时间:2023-11-30 20:43:57 24 4
gpt4 key购买 nike

我在这里看了很多问题,但我无法解决这个问题

$('.titular').select2({
placeholder: 'Select',
width: '100%',
ajax: {
url: "/ajax/ajax.php",
data: function(params) {
var query = {
query: params.term
}
return query;
},
processResults: function(data) {
console.log(data);

return {
results: $.map(data, function (item) {
return {
id: item.id,
nome: item.nome
}
})
};

},
},
escapeMarkup: function (markup) { return markup; }

});

还有我的 JSON:

[{"id":12,"nome":"Joe Bill"},{"id":13,"nome":"PJ"},{"id":14,"nome":"John"},{"id":16,"nome":"Acme"},{"id":17,"nome":"Acme2"},{"id":18,"nome":"Acme3"}]

结果未显示,开发者控制台显示:

jQuery.Deferred exception: Cannot use 'in' operator to search for 'length' in [{"id":16,"nome":"Acme"},{"id":17,"nome":"Acme2"},{"id":18,"nome":"Acme3"}] TypeError: Cannot use 'in' operator to search for 'length' in [{"id":16,"nome":"Acme"},{"id":17,"nome":"Acme2"},{"id":18,"nome":"Acme3"}]

我尝试使用在官方文档中查看的 JSON,但未成功...

感谢任何帮助

最佳答案

控制台错误意味着您正在向 map 传递一个字符串,因此您需要先将数据解析为 json。我做了一些测试,它是这样工作的:

processResults: function (data, params) {
data = JSON.parse('[{ "id": 12, "nome": "Joe Bill" }, { "id": 13, "nome": "PJ" }, { "id": 14, "nome": "John" }, { "id": 16, "nome": "Acme" }, { "id": 17, "nome": "Acme2" }, { "id": 18, "nome": "Acme3" }]');

var r = $.map(data, function (item) { return { id: item.id, text: item.nome }});
return { results: r };
}

希望这对您有所帮助。

关于javascript - 选择 2 并加载 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48935941/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com