[英]Returning from a nested function in javascript
I'm trying to make a function that uses jquery's ajaxfunction to get some info from my ajax.php file. 我正在尝试使用jquery的ajax函数来从我的ajax.php文件中获取一些信息。
code: 码:
function ajaxIt(dataLine){
$.ajax({
type: "POST",
url: "ajax.php",
data: "ajax=true&"+dataLine,
success: function(msg){
console.log("[AjaxIt]: "+dataLine+" returned "+msg);
return msg;
}
});
}
if(ajaxIt("action=loggedIn")=="1"){
console.log("Logged In");
loggedIn=true;
initiate2();
}
The problem is that I can't get the success function to return all the way to the ajaxIt function. 问题是我无法获得成功函数一直返回到ajaxIt函数。 Could anyone shed some light onto how I could do something like that?
任何人都可以阐明如何做到这样的事情吗?
Thanks. 谢谢。
You need to invoke a callback
function to process data that way: 您需要调用
callback
函数来处理数据:
function ajaxIt(dataLine, cb){
$.ajax({
type: "POST",
url: "ajax.php",
data: "ajax=true&"+dataLine,
success: function(msg){
if($.isFunction(cb))
cb.apply(null, [msg]);
}
});
}
ajaxIt("action=loggedIn", function(data){
if(data === "1"){
console.log("Logged In");
loggedIn=true;
initiate2();
}
});
$.ajax
is asynchronous. $.ajax
是异步的。 This means that it will return right away, instead of waiting for the AJAX query to execute and retrieve a result from the server. 这意味着它将立即返回,而不是等待AJAX查询执行并从服务器检索结果。 By the time the message from the server arrives, your
ajaxIt
function has already finished working. 当来自服务器的消息到达时,您的
ajaxIt
函数已经完成工作。
What you should use here is a continuation-passing style. 你应该在这里使用的是一种延续传递方式。 Provide
ajaxIt
with a continuation : a function that explains what should be done once ajaxIt
has finished working. 为
ajaxIt
提供一个延续 :一个函数,解释一旦ajaxIt
完成工作应该做什么。
function ajaxIt(data, continuation) {
data.ajax = true;
$.post("ajax;php", data, function(msg) {
console.log("[AjaxIt]: returned "+msg);
continuation(msg);
});
}
ajaxIt({action:"logged-in"}, function(result) {
if (result == "1") {
console.log("Logged In");
loggedIn=true;
initiate2();
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.