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


How to pass jquery post result to another function

我正在尝试使用jQuery验证插件来检查可用的名称。它将请求发布到php文件,并得到响应0或1。

问题是我无法将结果传递给主函数。请看下面的代码

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)  
}, "");

正如人们已经说过的,它是异步的,并且是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
}
}, "");

以上内容将允许您将结果传递给另一个函数,该函数将允许您在结果从服务器返回后访问和处理结果。