此時您不能return result
,因爲這是異步調用。相反,您可以退還承諾並解決問題。遵守以下...
function getCount() {
return $.ajax({
url: 'php/get.php',
type: 'get',
dataType: 'html',
data: { location: '', category: '10' },
});
}
與樣品的使用...
var result;
getCount().then(function(response) { // -- asynchronous
result = Math.ceil(response/20);
});
此外,一些語法速記可能有興趣在這裏 - jQuery.get()
function getCount() {
return $.get('php/get.php', { location: '', category: '10' });
}
JSFiddle Link - 演示
或者,如果你想與getCount()
執行您Math
邏輯,而不是你的then()
回調,你可以用下面的方式做到這一點...
function getCount() {
var deferred = $.Deferred();
$.get('php/get.php', { location: '', category: '10' }, function(response) {
deferred.resolve(Math.ceil(response/20));
});
return deferred.promise();
}
getCount().then(function(response) {
console.log(response) // Math.ceil value
});
JSFiddle Link - 二次演示
查看Deferred Object docs全面瞭解這裏發生了什麼
[如何從異步調用返回響應?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) –