【发布时间】:2017-06-16 18:25:07
【问题描述】:
我有一个 jQuery UI 自动完成问题,我试图通过大量研究来解决这个问题,但只是部分解决了它。我已经设法使用这段代码让它工作了:
$("#term").autocomplete({
source: function (request, response) {
$.ajax({
url: "https://wger.de/api/v2/exercise/?format=json",
type: "GET",
data: { name: request.term },
dataType: "json",
success: function(data) {
response($.map(data, function(item) {
return {
label: item,
value: item
}
}));
}
});
}
});
我正在使用 JSON 中的开源 API,这是一个示例:
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"id": 436,
"license_author": "Andrew Carothers",
"status": "1",
"description": "<p>1 Minute for each exercise</p>\n<ol>\n<li>Hold feet 6 inches off ground</li>\n<li>Crunches</li>\n<li>Side Crunches (L)</li>\n<li>Side Crunches (R)</li>\n<li>Heel Touches</li>\n<li>Plank Crunch</li>\n<li>Scissor Kicks</li>\n<li>Swim Kicks</li>\n<li>V Crunches</li>\n<li>Hold feet 6 in off ground</li>\n</ol>\n<p>Exercises can be substituted to vary workout</p>",
"name": "10 Min Abs",
"name_original": "10 Min Abs",
"creation_date": "2016-12-09",
"uuid": "3c5f6e1c-cb22-4a9f-a13e-d14afeb29175",
"license": 2,
"category": 10,
"language": 2,
"muscles": [],
"muscles_secondary": [],
"equipment": []
}
]
}
我想通过 JSON 中的“名称”字母获得自动完成建议,但我得到了整个 JSON 数组,即使对象不存在。我已经尝试过item.results[0].name,但我得到的一切都是TypeError: item.results is undefined。 如何修改$.ajax以获取自动补全建议中JSON对象的“名称”值?
感谢您的帮助。
【问题讨论】:
-
您收到的错误表明您提供给我们的数据对象不是您收到的。如果没有您收到的数据的真实表示,我们将无法为您提供帮助。
-
@KevinB 好吧,我每次都检查 Firefox 的网络监视器,我得到了很好的 URL,json 类型,例如wger.de/api/v2/exercise/?format=json&name=10+Min+Abs
-
data.results.map(...
标签: javascript jquery json ajax autocomplete