从 javascript 中的嵌套函数返回
我正在尝试创建一个使用 jquery 的 ajaxfunction 从我的 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();
}
问题是我无法让 success 函数一路返回到 ajaxIt 函数。有人能告诉我如何做这样的事情吗?
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要调用回调函数来以这种方式处理数据:
You need to invoke a
callback
function to process data that way:$.ajax
是异步的。这意味着它将立即返回,而不是等待 AJAX 查询执行并从服务器检索结果。当来自服务器的消息到达时,您的ajaxIt
函数已经完成工作。这里你应该使用的是延续传递风格。为
ajaxIt
提供延续:一个解释ajaxIt
完成工作后应该执行的操作的函数。$.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, yourajaxIt
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 onceajaxIt
has finished working.