当使用搜索客户信息时,我有两个 jQuery AJAX 请求。我可以通过 .autocomplete 获取客户名称,也可以从 addressSearch.php 获取 JSON 数据,但是当我无法从第二个 JSON 集中获取所需的值时。
用户应该简单地从下拉列表中选择地址,我应该填写表格。
当我console.log(address)
没有得到正确的多维数组时。
如何选择正确的子数组将数据发送到表单域?
HTML
<label>Customer Search:</label><input id="cSearch" type="text" /><br />
<label>Name:</label><input id="name" /><br />
<select id="addresses">
<option>Please Select Address</option>
</select>
<label>Street:</label><input id="street" type="text" /><br />
<label>City:</label><input id="city" type="text" /><br />
<label>State:</label><input id="state" type="text" /><br />
<label>Zip:</label><input id="zip" type="text" /><br />
JavaScript
$(document).ready(function() {
$("input#customerSearch").autocomplete({
source:'inc/customerSearch.php',
select: function(event, ui) {
$('#name').val(ui.item.name);
getAddresses(ui.item.addressid);
},
minLength:2
});
});
var address = [];
function getAddresses(id){
$.getJSON(
'inc/addressSearch.php',
{ id: id },
function(data) {
$('#addresses').children().remove().end().append('<option>Please Select Address</option>');
$.each(data, function(x, val) {
$('#addresses').append('<option value="' + val['addressid'] + '">'+ val['street1'] +'</option>');
address[x] = [];
$.each(val, function(key, value) {
address[x][key] = value;
});
});
}
);
$('select#addresses').change(function() {
var j = $(this).val();
//fill in fields when select
});
}
地址搜索.php
$id = explode(',', $id);//explode address ids
$data = array();//data array
foreach($id as $id) {//evaluate each address
$query = "SELECT * FROM `address` WHERE address_id = '". $id ."'";//query
$result = mysql_query($query);//run query
if (mysql_num_rows($result)) {//results exist
while($row = mysql_fetch_assoc($result)) {//loop
$data[$id] = array(//build array
'addressid' => $row['address_id'],
'street1' => $row['address_street1'],
'street2' => $row['address_street2'],
'city' => $row['address_city'],
'region' => $row['address_region'],
'country' => $row['address_country'],
'code' => $row['address_code']
);
}
}
}
print json_encode($data);// jQuery wants JSON data
JSON
{
"101":{
"addressid":"101",
"street1":"123 ABC St",
"street2":"",
"city":"Somewhere",
"region":"AB",
"country":"USA",
"code":"12345"
},
"102":{
"addressid":"102",
"street1":"123 10th St",
"street2":"Apt 101",
"city":"Nowhere",
"region":"AB",
"country":"USA",
"code":"12345"
}
}