Javascript 从Ajax调用返回值
我试图从Ajax调用返回一个值,但找不到正确的方法。以下是我现在拥有的:Javascript 从Ajax调用返回值,javascript,jquery,ajax,Javascript,Jquery,Ajax,我试图从Ajax调用返回一个值,但找不到正确的方法。以下是我现在拥有的: function getCount() { $.ajax({ url: "php/get.php", type: 'get', dataType: 'html', data: { location: "", category: "10" }, async: false, success: function(data) {
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;
}
正如您所看到的,我使用了async false,现在它已经贬值了。是否有其他方法可以像我现在这样从函数返回此值,而不使用
async:false
?此时无法返回结果,因为这是一个异步调用。相反,你可以回报一个承诺并解决它。注意以下几点
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);
});
此外,此处可能对某些速记语法感兴趣-
-演示
或者,如果您希望使用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()Math.ceil值以供使用,我将如何存储该值?我会让变量等于getCount()。然后(函数(响应){})代码>?不幸的是,您不能完全那样做。典型的方法是声明一个空变量,然后在承诺解析后使用它,或者在then()
回调中,或者在某个事件处理程序函数中(解析后的任何位置)。如果您尝试在回调下面使用它,您将得到未定义的
。我为你学习,我包括了一些评论,希望能有所帮助!好的,很有趣。因此,如果我想要获得该值,我需要将代码放在then()
中,并像那样处理它,而不是试图检索它?这是正确的,请记住,您可以始终在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
});