ajax is asynchronous, the code you have would return before the ajax request has finished.
There are a few ways you can restructure your code.
您可以在请求完成后执行回溯功能中通过。
function getSearch(url, callback) {
$.getJSON(url, function(data) {
var out = ;
// btw what is numResults ??
for(var i = 0; i < numResults; i++) {
out += <p class="hash_list"> + <a href="http://www.twitter.com/ + data.results[i].from_user + "> + data.results[i].from_user + </a>: + data.results[i].text + </p> ;
}
if( typeof callback === function ) callback( out );
});
}
然后你会像这样使用这个函数。
getSearch( test.php , function(out){
// here you can use the out variable
});
或者你可以使用 jquery 延后回一个承诺, 并在解决延后时作为争论的一部分, 传递变量作为参数 。 这里举一个例子 。
function getSearch()
{
var deferred = $.Deferred();
$.getJSON(url, function(data) {
var out = ;
// btw what is numResults ??
for(var i = 0; i < numResults; i++) {
out += <p class="hash_list"> + <a href="http://www.twitter.com/ + data.results[i].from_user + "> + data.results[i].from_user + </a>: + data.results[i].text + </p> ;
}
deferred.resolve( out ); // resolve the request and pass in the out argument.
});
return deferred.promise(); // return a promise
}
$.when( getSearch() ).then(function( out ){ // the out variable will get passed in
console.log( out );
});