Javascript AJAX函数返回undefined而不是true / false

编程入门 行业动态 更新时间:2024-10-08 08:30:15
本文介绍了Javascript AJAX函数返回undefined而不是true / false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个函数发出AJAX调用(通过jQuery)。在 complete 部分中,我有一个函数说:

complete: function(XMLHttpRequest,textStatus) { if(textStatus ==success) { return(true); } else { return(false);但是,如果我这样调用:

if(callajax()) { //做某事} else { //其他}

如果我在完成中设置了警报(textStatus) / code>函数我得到真,但不是之前该函数返回 undefined 。

是否可以将回调函数传递给我的 callajax()方法?像:

callajax(function(){// success},function(){// error},function });

解决方案

a 回调功能。它将被Ajax对象异步调用! - 操作完成时。没有办法捕获回调的结果,只有Ajax对象可以这样做。

您的 callajax() function - 你不显示那个函数,但我认为它只是使Ajax调用 - 不能返回调用的结果(=响应头和正文),因为调用将不会完成,当你退出 callajax()函数。

更新:也很可能进行同步AJAX调用。感谢@Andris指出这一点。在jQuery中,您需要将 async 选项设置为 false :Docs 此处。但是,即使是那些使用标准的回调函数,只要我能看到,所以你想要的方法返回 false 或 true 可能仍然不工作。

I have a function that issues an AJAX call (via jQuery). In the complete section I have a function that says:

complete: function(XMLHttpRequest, textStatus) { if(textStatus == "success") { return(true); } else { return(false); } }

However, if I call this like so:

if(callajax()) { // Do something } else { // Something else }

The first is never called.

If I put an alert(textStatus) in the complete function I get true, but not before that function returns undefined.

Would it be possible to pass a callback function to my callajax() method? Like:

callajax(function(){// success}, function(){// error}, function(){// complete});

解决方案

complete is a callback function. It will be invoked by the Ajax object - asynchronously! - when the operation is complete. There is no way for you to catch the callback's result, only the Ajax object could do that.

Your callajax() function - you're not showing that function but I assume it simply makes the Ajax call - can not return the call's result (= the response headers and body), as the call will not have been finished yet when you exit the callajax() function.

Update: It is also well possible to make synchronous AJAX calls. Thanks to @Andris for pointing this out. In jQuery, you need to set the async option to false: Docs here. However, even those use the standard callback functions as far as I can see, so your desired method of returning false or true may still not work.

更多推荐

Javascript AJAX函数返回undefined而不是true / false

本文发布于:2023-11-27 21:33:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1639679.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   而不是   Javascript   AJAX   false

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!