我正在 ajax 调用中创建一个国家/地区列表,它是一个对象数组:
$.ajax({
url: '//maps.googleapis.com/maps/api/geocode/json?address=' + zipCode + '®ion=AT',
type: 'GET',
dataType: 'json',
success: function (res){
var countryList = [];
... ...
... ...
countryList.push({
label: countryCode + ' ' + countryName,
value: result[0]['id'],
countryId: result[0]['id'],
countryCode: countryCode,
countryName: countryName,
city: city
});
zipCodeSelector.autocomplete({
source: countryList
});
}
})
自动完成的响应是
No search results
对象看起来像这样:
[Object]
0: Object
city: "Berlin"
countryCode: "DE"
countryId: "a7c40f631fc920687.20179984"
countryName: "Germany"
label: "DE Germany"
value: "a7c40f631fc920687.20179984"
我在ajax中调用自动完成函数。这是一个问题还是还有其他问题?
最佳答案
您可以在源选项中调用 ajax 方法,而不是先填充数组。
source
选项接受自定义函数请参阅:
Function: The third variation, a callback, provides the most flexibility and can be used to connect any data source to Autocomplete. The callback gets two arguments: A request object, with a single term property, which refers to the value currently in the text input. For example, if the user enters "new yo" in a city field, the Autocomplete term will equal "new yo". A response callback, which expects a single argument: the data to suggest to the user. This data should be filtered based on the provided term, and can be in any of the formats described above for simple local data. It's important when providing a custom source callback to handle errors during the request. You must always call the response callback even if you encounter an error. This ensures that the widget always has the correct state. When filtering data locally, you can make use of the built-in $.ui.autocomplete.escapeRegex function. It'll take a single string argument and escape all regex characters, making the result safe to pass to new RegExp().
代码:
$("#autocomplete").autocomplete({
source: function (req, resp) {
$.ajax({
url: '//maps.googleapis.com/maps/api/geocode/json?latlng=55.397563, 10.39870099999996&sensor=false',
type: 'GET',
dataType: 'json',
success: function (res) {
resp($.map(res.results, function (item) {
return {
label: item.formatted_address,
value: item.place_id
};
}));
}
})
}
});
关于javascript - Jquery 自动完成功能不起作用 - 没有搜索结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29631093/