如何将jquery post结果传递给另一个函数

问题描述:

我试图使用jQuery validate插件来检查可用的名称。 它对php文件发布请求并获得响应0或1.如何将jquery post结果传递给另一个函数

问题是我无法将结果传递给主函数。 请参阅下面

jQuery.validator.addMethod("avaible", function(value, element) { 

    $.post("/validate.php", { 
     friendly_url: value, 
     element:element.id 
    }, function(result) { 
     console.log(result) 
    }); 

    //How to pass result here??? 
    console.log(result) 
}, ""); 
+1

'myOtherFunction(result)' – adeneo 2015-02-11 00:37:18

+2

欢迎来到异步JavaScript的世界。 – 2015-02-11 00:42:26

+0

因为'console.log()'是一个函数,所以你实际上已经用'console.log(result)'来完成它了。 (即另一个函数,但不能返回到调用该函数的函数开始) – developerwjk 2015-02-11 00:45:07

所以人们已经说过,它是异步的,它是myOtherFuntion :-)

我只是结合这些评论到某种形式的答案我对你的代码:

function myOtherFunction(result) { 
// here you wrote whatever you want to do with the response result 
//even if you want to alert or console.log 
    alert(result); 
    console.log(result); 
} 

jQuery.validator.addMethod("avaible", function(value, element) { 

    $.post("/validate.php", { 
     friendly_url: value, 
     element:element.id 
    }, function(result) { 
     myOtherFunction(result); 
    }); 

    //How to pass result here??? 

    //there is no way to get result here 
    //when you are here result does not exist yet 
}, ""); 

由于Javascript的异步特性,console.log(result)将不起作用,因为服务器尚未返回结果数据。

jQuery.validator.addMethod("avaible", function(value, element) { 

$.post("/validate.php", { 
    friendly_url: value, 
    element:element.id 
}, function(result) { 
    console.log(result); 
    doSomethingWithResult(result); 
}); 

function doSomethingWithResult(result) { 
    //do some stuff with the result here 
} 
}, ""); 

以上将允许您将结果传递给另一个函数,这将让你实现访问和处理结果的工作一旦从服务器返回。