[英]Return value from an Ajax call
我正在尝试从Ajax调用返回一个值,但是无法找到正确的方法来执行此操作。 这是我现在所拥有的:
function getCount() {
$.ajax({
url: "php/get.php",
type: 'get',
dataType: 'html',
data: { location: "", category: "10" },
async: false,
success: function(data) {
result = Math.ceil(data/20);
}
});
return result;
}
如您所见,我使用了现在已贬值的异步false。 您是否有另一种方法可以从函数中像现在这样返回此函数,而无需使用async: false
?
您目前无法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' });
}
另外,如果您希望使用getCount()
而不是then()
回调来执行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文档 ,以获取有关此处发生情况的全面概述
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.