【问题标题】:autocomplete jquery-ui with json data is not working small glitch带有 json 数据的自动完成 jquery-ui 不起作用
【发布时间】:2014-03-06 00:44:57
【问题描述】:

我在 javascript 中有这段代码:

$("#lcountry").autocomplete({
    source: function (request, response) {
         $.ajax({
             url: "https://graph.facebook.com/search?type=adcountry&limit=3",
             type: "GET",
             data: request,
             success: function (data) {
                 response($.map(data, function (el) {
                     return {
                         label: el.name,
                         value: el.country_code
                     };
                 }));
             }
         });
    },
    select: function (event, ui) {
        // Prevent value from being put in the input:
        this.value = ui.item.label;
        // Set the next input's value to the "value" of the item.
        $(this).next("input").value(ui.item.value);
        event.preventDefault();
    }
});

不幸的是,这不起作用。当我在这里查看控制台时,显然我们可以看到国家/地区,我希望能够在 jquery 自动完成中返回名称值:

{
   "data": [
      {
         "country_code": "US",
         "name": "United States",
         "supports_region": "true",
         "supports_city": "true"
      },

      {
         "country_code": "AR",
         "name": "Argentina",
         "supports_region": "false",
         "supports_city": "true"
      },
      {
         "country_code": "AU",
         "name": "Australia",
         "supports_region": "true",
         "supports_city": "true"
      }
   ],
   "paging": {
      "next": "https://graph.facebook.com/search?type=adcountry&limit=5&term=c&offset=5"
   }
}

【问题讨论】:

    标签: javascript jquery json jquery-ui


    【解决方案1】:

    您需要使用 data.data - data 是一个对象,其中包含具有国家/地区列表的键 data

    $("#lcountry").autocomplete({
        source: function (request, response) {
            $.ajax({
                url: "https://graph.facebook.com/search?type=adcountry&limit=3",
                type: "GET",
                data: request,
                success: function (data) {
                    response($.map(data.data, function (el) {
                        return {
                            label: el.name,
                            value: el.country_code
                        };
                    }));
                }
            });
        },
        select: function (event, ui) {
            // Prevent value from being put in the input:
            this.value = ui.item.label;
            // Set the next input's value to the "value" of the item.
            $(this).next("input").value(ui.item.value);
            event.preventDefault();
        }
    });
    

    演示:Fiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-02
      • 2011-02-02
      相关资源
      最近更新 更多