自动完成jquery-ui与json数据不起作用小故障

时间:2014-03-06 00:44:57

标签: javascript jquery json jquery-ui

我在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"
   }
}

1 个答案:

答案 0 :(得分: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