我有一个AJAX请求来显示用户邮政编码的地址列表。它将在下拉列表中显示它们供用户选择。我在下面展示了PHP,JS和repsonse。
我使用cURL获得了JSON响应。我正在使用CI和jQuery。
如何从响应中提取我需要的数据并将它们放入HTML选项标记中。 ID将出现在选项值标签中,描述将介于开始和结束选项标签之间。
这是我的JS:
$.get(
'<?=site_url('api/postcode') ?>',
{
'postcode' : postcode
},
function(data) {
$( '#loader-address' ).hide();
// Show the dropdown list
var list = '<option value="">Choose...</option>';
// Create address options from JSON
},
'json'
);
这是我的PHP函数:
public function get_by_postcode( $postcode )
{
/* Build up the URL to send the request to. */
$sURL = "http://services.Postcodeanywhere.co.uk/json.aspx?";
$sURL .= "account_code=" . urlencode($this->pca->account);
$sURL .= "&license_code=" . urlencode($this->pca->license);
$sURL .= "&action=lookup";
$sURL .= "&type=by_Postcode";
$sURL .= "&postcode=" . urlencode($postcode);
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$sURL);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$ContentsFetch = curl_exec($ch);
curl_close($ch);
return $ContentsFetch;
}
这是JSON respone:
"[{\"id\":\"5378660.00\",\"seq\":\"0\",\"description\":\"1 Carrington Close Croydon\"},\r\n{\"id\":\"5378661.00\",\"seq\":\"1\",\"description\":\"2 Carrington Close Croydon\"},\r\n{\"id\":\"5378662.00\",\"seq\":\"2\",\"description\":\"3 Carrington Close Croydon\"},\r\n{\"id\":\"5378663.00\",\"seq\":\"3\",\"description\":\"4 Carrington Close Croydon\"},\r\n{\"id\":\"5378664.00\",\"seq\":\"4\",\"description\":\"5 Carrington Close Croydon\"},\r\n{\"id\":\"5378665.00\",\"seq\":\"5\",\"description\":\"6 Carrington Close Croydon\"},\r\n{\"id\":\"5378666.00\",\"seq\":\"6\",\"description\":\"7 Carrington Close Croydon\"},\r\n{\"id\":\"5378667.00\",\"seq\":\"7\",\"description\":\"8 Carrington Close Croydon\"}]\r\n"
答案 0 :(得分:0)
您可以在javascript中使用data.id
。结合jQuery $.each()
函数迭代数据。像这样:
$.get(
'<?=site_url('api/postcode') ?>',
{
'postcode' : postcode
},
function(data) {
$( '#loader-address' ).hide();
// Show the dropdown list
var list = '<option value="">Choose...</option>';
$.each(data, function(key, value) {
list += '<option value="'+value.id+'">'+value.description+'</option>';
});
// Create address options from JSON
},
'json'
);
答案 1 :(得分:0)
使用getJSON
http://api.jquery.com/jQuery.getJSON/
$.getJSON(url, param ,function(data) { //url - return json page
$( '#loader-address' ).hide();
var list = '<option value="">Choose...</option>';
$.each(data, function() {
list += '<option value="'+this.id+'">'+this.description+'</option>';
});
};
javascript中的json响应必须为"[{"id":"5378660.00","seq":"0","description":....
。逃脱报价不需要