问题描述
我有一个code,它从嵌套函数返回值给出的问题。结果
检查这个code。
i have a code that give problem on returning value from nested function.
check this code.
function test(){
var flag=true;
$.post('path/of/file.php',{data:data},function(r){
if(r == 1){ flag=false; }
});
return flag;
}
此功能测试
总是返回真正
。因为它没有回电 $的功能等待返回值。发布
。如果我在回调函数中返回它是不行的。因此,如何从这个问题的解决。结果
谢谢...
this function test
always return true
. because it return value without waiting of call back function of $.post
. if i return within the callback function it is not work. so, how can i overcome from this problem.
thanks...
推荐答案
由于运行.post的异步你的方法总是在瞬间返回true。但如何对返回反对呢?我知道这是不是你问了一个不同的方法,它可能并不适用于您的方案。
Since .post runs async your method will always return true at the moment. But how about returning a deferred object instead? I realize that this is a different approach than the one you're asking for, and it might not be applicable for your scenario.
这样的事情(从我的头顶):
Something like this (from the top of my head):
function test(){
var def = new $.Deferred();
$.ajax({
url: 'test',
success: function(data) {
// Do some minor logic to determine if server response was success.
console.log('success in callback');
if(data == true){
def.resolve(true);
}
else{
def.reject();
// or possibly def.resolve(true) depending what you're looking for.
}
},
error:function(){
console.log('error in callback');
def.reject();
}
});
return def;
}
function testMethod(){
var defObject = test();
defObject.done(function(result){
console.log('done in deferred');
// Do something when everything went well.
}).fail(function(){
console.log('error in deferred');
// Do something when something went bad.
});
}
$(document).ready(function(){
testMethod();
});
递延
可以很容易地听异步回调。这是当你想要做一些逻辑,一个至关重大要求完成一个共同的模式,而是要在逻辑与请求本身分开。
Deferred makes it easy to listen async callbacks. It's a common pattern when you want to do some logic efter a request is done, but you want to separate the logic from the request itself.
更多的例子在这里:
的
一个plunkr例如:
http://plnkr.co/edit/LsNjfx4alNzshOQb2XAW?p=$p$pview一>
A plunkr example:http://plnkr.co/edit/LsNjfx4alNzshOQb2XAW?p=preview
这篇关于从jQuery的嵌套函数的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!