jquery execution order
Consider the following code:
function searchText() {
if($('#searchtext').val() == null || $('#searchtext').val().trim() == '') {
alert('must provide a text to search for');
return false;
}
urllink='http://search.twitter.com/search.json?q=' + escape($('#searchtext').val().trim()) + '&callback=?';
$('#results').html(urllink);
$.getJSON(urllink,function(data) {
var resultT = {};
$('#results').html(data.results[0].profile_image_url);
return data.results;
});
}
$('#gosearch').click(function() {
var data = searchText();
if(data == null)
alert('null');
return false;
});
I have a breakpoint in firebug in return data.results
of searchText()
. But it seems that searchText
is executed but I do not stop in my break point. It rather checks for data, which is null
, and executes alert('null')
. then it stops in my break point inside searchText
.
Why is this happening? Can't I execute functions inside events and wait them to finish before moving to next line in code?
thanks
You did not realize that AJAX is Asynchronous. So when searchText()
returns the ajax request hasn't finished yet. You need to pass it a callback and execute that instead of doing return data.results;
.
Here's an example:
function searchText(callback) {
if ($('#searchtext').val() == null || $('#searchtext').val().trim() == '') {
alert('must provide a text to search for');
return false;
}
urllink = 'http://search.twitter.com/search.json?q=' + escape($('#searchtext').val().trim()) + '&callback=?';
$('#results').html(urllink);
$.getJSON(urllink, function (data) {
var resultT = {};
$('#results').html(data.results[0].profile_image_url);
callback(data.results);
});
}
$('#gosearch').click(function(e) {
e.preventDefault();
searchText(function(data) {
if (data == null) alert('null');
// do something with your data
});
});
You are getting data asynchronously from urllink and the function where the return data.result resides is a callback function which will be called when the call to the url is complete.
The subsequent code will not wait for the asynchronous call to complete.
精彩评论