Javascript 如何将jquery post结果传递给另一个函数
我正在尝试使用jQuery验证插件来检查可用的名称。 它将请求发送到php文件并获得响应0或1 问题是我无法将结果传递给主函数。 请看下面我的代码Javascript 如何将jquery post结果传递给另一个函数,javascript,php,jquery,Javascript,Php,Jquery,我正在尝试使用jQuery验证插件来检查可用的名称。 它将请求发送到php文件并获得响应0或1 问题是我无法将结果传递给主函数。 请看下面我的代码 jQuery.validator.addMethod("avaible", function(value, element) { $.post("/validate.php", { friendly_url: value, element:element.id }, function(resul
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)
}, "");
正如人们已经说过的,它是异步的,也是我的功能:- 我只是将这些评论组合成某种回答:
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.logresult将无法工作,因为服务器尚未返回结果数据
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
}
}, "");
上述操作将允许您将结果传递给另一个函数,该函数将允许您在结果从服务器返回后访问并使用该结果。myOtherFunctionresultWelcome到异步javascript的世界。您实际上已经在使用console.logresult进行此操作,因为console.log是一个函数。即,返回到另一个函数,但不能返回到调用post的函数