My scenario is this:
When the page is loaded, a listbox with countries is loaded.By selecting an item from a dropw down list, a country item in the listbox is selected using jQuery.
Now that a country is selected in the listbox, I call a function which retrieves cities and populate a city listbox.
The code looks something like this:
$('#MyDropDownList').change(function() {
(...) // Selected country is set here
populateCityListBox();
//this alert is undefined. Probably because it's triggered before the callback in populateCityListBox()
alert(jQuery('#cityListBox option[value=Oslo]').val());
});
function populateCityListBox()
{
//Get ID for selected country
var ctryID = jQuery("select#countryListBox").val();
jQuery.post("wp-content/themes/storelocator/include/jquery_bll.php", { instance: 'getCitiesByCountry', countryID: ctryID },
function(data)
{
var options = '';
for (var i = 0; i < data.length; i++) {
options += '<option value="' + data[i].city + '">' + data[i].city + '</option>';
}
jQuery("select#cityListBox").html(options);
// This alerts the option text, which also is Oslo
alert(jQuery('#cityListBox option[value=Oslo]').val());
}, "json");
}
My problem is this: I'm not able to retrieve values in the city listbox after I have run the function populateCityListBox();
. I am able to retrieve values in the $.post 开发者_如何学JAVAcallback.
What can I do to be able to retrieve the values after the function is triggered? (I know it has to do something with some stuff being callback, while others run "realtime"... or something like that).
You are correct. Since your request is asynchronous, the code keeps on running. You could potentially substitute something like so:
$('#MyDropDownList').change(function() {
(...) // Selected country is set here
populateCityListBox(function () {
//this alert should work now
alert(jQuery('#cityListBox option[value=Oslo]').val());
});
});
function populateCityListBox(callback)
{
//Get ID for selected country
var ctryID = jQuery("select#countryListBox").val();
jQuery.post("wp-content/themes/storelocator/include/jquery_bll.php", { instance: 'getCitiesByCountry', countryID: ctryID },
function(data)
{
var options = '';
for (var i = 0; i < data.length; i++) {
options += '<option value="' + data[i].city + '">' + data[i].city + '</option>';
}
jQuery("select#cityListBox").html(options);
// This alerts the option text, which also is Oslo
alert(jQuery('#cityListBox option[value=Oslo]').val());
callback();
}, "json");
}
By placing callback
as an argument of populateCityListBox
, we are able to call that function inside of your change
up there. In essence, it is just a 'modified' callback of sorts: we are just executing yet another function in the callback. This lets you run the function populateCityListBox
independently in a console like you could and still be able to use the application logic or whatnot.
Hope this helps.
精彩评论