我需要填写城市下拉列表并使用城市机场代码设置值,我有以下jquery代码,我想知道它有什么问题吗?它没有填写下拉列表
<script>
$(document).ready(function () {
$(function (request, response) {
$.ajax({
url: "http://iatacodes.org/api/v4/cities",
jsonp: "callback",
dataType: "jsonp",
data: {
api_key: "XXX-XXXX-XXXXXX-XXXXX"
},
success: function (data) {
if (data) { // success
response($.map(data, function (item) {
return $('<option>').val(item.code).text(item.name);
})).appendTo('#Cities');
} else { // no results
response();
}
}
});
});
});
</script>
<select class="selectpicker" id="Cities" name="Cities">
<option value="" selected>Select City</option>
</select>
缩短原始数据
{"request":{"lang":"en","currency":"THB","time":81,"id":"babdee58-12c3-4ea2-b4c5-db750f646c6a","server":"a","pid":24092,"key":{"id":4870,"api_key":"XXXX-XXXX-XXXX-XXXX-XXXXXXX","type":"free","expired":null,"registered":"2015-11-27T05:16:52.000Z","affiliate_account":0,"affiliate_currency":"USD","affiliate_percent":33,"affiliate_paypal":"Hi, if you want to be our partner just contact us info@iatacodes.org","limits_by_hour":2500,"limits_by_minute":250,"usage_by_hour":12,"usage_by_minute":0},"params":{"lang":"en"},"client":{"country_code":"PH","country":"Philippines","city":"Makati","lat":14.566699999999997,"lng":121.0333,"ip":"112.199.36.67"}},"response":[{"code":"AAA","country_code":"PF","name":"Anaa","lat":-17.05,"lng":-145.41667,"updated":"2015-10-05T18:07:47.000Z"},{"code":"AAB","country_code":"AU","name":"Arrabury","lat":-26.7,"lng":141.04167,"updated":"2015-10-07T16:33:06.000Z"},{"code":"AAC","country_code":"EG","name":"El Arish","lat":31.133333,"lng":33.75,"updated":"2015-10-07T15:57:39.000Z"},{"code":"AAE","country_code":"DZ","name":"Annaba","lat":36.821392,"lng":7.811857,"updated":"2015-10-05T18:07:47.000Z"},{"code":"AAF","country_code":"US","name":"Apalachicola","lat":29.733334,"lng":-84.98333,"updated":"2015-10-07T15:57:39.000Z"},{"code":"AAG","country_code":"BR","name":"Arapoti","lat":-24.103611,"lng":-49.79,"updated":"2015-10-07T15:57:39.000Z"}
答案 0 :(得分:0)
您可以使用$.map()
迭代$.each()
数组中的项目,并在每次迭代时附加data.response
元素,而不是使用option
函数:
$.each(data.response, function (_, item) {
$('<option></option>').val(item.code).text(item.name).appendTo('#Cities');
});
所以你的成功回调将是:
success: function (data) {
if (data) {
$.each(data.response, function (_, item) {
$('<option></option>').val(item.code).text(item.name).appendTo('#Cities');
});
} else {
// no result
}
}
答案 1 :(得分:0)
http://iatacodes.org/api/v4/cities.jsonp?api_key=YOUR-API-KEY&callback=yourJSMethodName
只需添加 .jsonp 和&amp; callback = yourJSMethodName