简体   繁体   English

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

[英]How to pass jquery post result to another function

I'm trying to use jQuery validate plugin to check available names. 我正在尝试使用jQuery validate插件来检查可用的名称。 It do post request to php file and get response 0 or 1. 它会向php文件发送请求并获得响应0或1。

The problem is that I cannot pass result to main function. 问题是我无法将结果传递给main函数。 please see my code below 请在下面查看我的代码

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

So as people already said, it is asynchronous and it is myOtherFuntion :-) 所以正如人们已经说过的那样,它是异步的,它是myOtherFuntion :-)

I just combine those comment into some kind of answer for you: 我只是将这些评论结合到某种答案中:

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

Due to the asynchronous nature of Javascript, console.log(result) will not work because the server has not returned with the result data 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
}
}, "");

The above will allow you to pass the result to another function which will allow you to achieve accessing and working with the result once it has returned from the server. 上面的代码将允许您将结果传递给另一个函数,一旦结果从服务器返回,就可以实现对结果的访问和处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM