【问题标题】:jQuery UI autocomplete in AJAX/JSONAJAX/JSON 中的 jQuery UI 自动完成
【发布时间】: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


【解决方案1】:

这行得通吗:

$("#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.results, function(index,item) {
                        return {
                            label: item.name,
                            value: item.name
                        }
                    }));
                }
            });
        }
    });

【讨论】:

  • 不,我已经试过了,回复是TypeError: item is null
  • 在 $.each 回调中,第一个参数是索引,第二个是值,对不起,我不好
  • 好的,它可以工作,但是只有当您在输入中输入 100% 正确的名称时才会出现建议,在名称正确之前它不会提出任何建议,因为脚本正在查找不存在的 JSON数组。
猜你喜欢
  • 2014-11-22
  • 2012-08-04
  • 2014-10-09
  • 1970-01-01
  • 1970-01-01
  • 2018-01-18
  • 1970-01-01
  • 2011-04-02
  • 1970-01-01
相关资源
最近更新 更多