admin管理员组文章数量:1323714
I'm trying to make a function that uses jquery's ajaxfunction to get some info from my ajax.php file.
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. Could anyone shed some light onto how I could do something like that?
Thanks.
I'm trying to make a function that uses jquery's ajaxfunction to get some info from my ajax.php file.
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. Could anyone shed some light onto how I could do something like that?
Thanks.
Share Improve this question asked Aug 18, 2010 at 14:56 Thomas Van NuffelThomas Van Nuffel 1,6892 gold badges12 silver badges6 bronze badges2 Answers
Reset to default 9You need to invoke a callback
function to process data that way:
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. This means that it will return right away, instead of waiting for the AJAX query to execute and retrieve a result from the server. By the time the message from the server arrives, your ajaxIt
function has already finished working.
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.
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();
}
});
本文标签: jqueryReturning from a nested function in javascriptStack Overflow
版权声明:本文标题:jquery - Returning from a nested function in javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742128236a2422039.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论