I am trying to populate a select box (cities related to a state) using the $.ajax method of jquery.
I wrote the following in my php script
$('#cmbState').change(function(){
$('#cmbCity').children().remove();
$.ajax({
type: "POST",
url: "../include/ajax.php",
data: "option=getCitiesList&stateid="+$(this).val()+"",
dataType: "json",
complete: function(response){
'what should I write in here ..?'
},
beforeSend: function(){$('#cmbCity').addClass('show_loading_in_center')},
success: function(){$('#cmbCity').removeClass('show_loading_in_center')}
});开发者_高级运维
});
and in the file 'ajax.php' (file where the query is sent for getting the realted cities) I did
$i=0;
foreach($cities as $city)
{
$response[$i]['id'] = $city['pk_cityid'];
$response[$i]['name'] = $city['name'];
$i++;
}
echo json_encode($response);
Now the response comes as XMLHTTPResponse object. How shall I populate the response into cities selectbox.?
Please help, I am really stuck over here.
Thanks
$('#cmbState').change(function () {
$.ajax({
type: "POST",
url: "../include/ajax.php",
data: {option: "getCitiesList", stateid: $(this).val()},
dataType: "json",
success: function (data) {
var $cmbCity = $('#cmbCity').empty();
$.each(data, function () {
$cmbCity.append('<option value="' + this.id + '">' + this.name + '</option>')
});
},
beforeSend: function(){ $('#cmbCity').addClass('show_loading_in_center') },
complete: function(){ $('#cmbCity').removeClass('show_loading_in_center') }
});
});
You need to write a success
handler that will be called with the data passed (completed
is called even on error). The data is passed as the first argument. We first empty()
the select and assign it to $cmbCity
for performance reasons. Then we iterate over data
using $.each
(cross-browser jQuery iteration) that binds each of the elements to this
. Using that we create new options in the #cmbCity
select.
The above code assumes that the response is in the following format:
[{"id": 1, "name": "London"},
{"id": 2, "name": "Paris"},
{"id": 3, "name": "New York"}]
Also, note that data
(in the $.ajax call above) is in key-value format - jQuery will serialize it automatically.
精彩评论