【问题标题】:How to add callback to AJAX variable assignment如何为 AJAX 变量赋值添加回调
【发布时间】:2011-05-16 10:40:20
【问题描述】:

我有一个变量 responce,它是通过 AJAX 函数 send() 分配的。当我做任务时...

responce = send();

在发送之前回复返回给我一个undefined 如何添加回调以防止这种情况发生?

编辑:澄清我的要求..

它仍然返回未定义。我正在使用函数 send send 返回 onreadystatechange 分配变量,但是当我的代码正在执行时.. 在 send() 可以返回之前,响应返回为未定义。如何停止响应下的代码运行,直到响应被分配发送值?

EDIT2:

以下代码是我的发送函数...

 function send(uri)
{
    var xhr = new XMLHttpRequest();
    xhr.open("POST",uri,true);
    xhr.onreadystatechange = function (send){
        if(xhr.readyState == 4){
            return xhr.responseText;
        }   
    }
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
    xhr.send(null);
}

【问题讨论】:

  • 请提供一些代码以获得更好的答案,没有看到一些代码很难给出答案。

标签: javascript ajax


【解决方案1】:

您正在以异步方式使用 Ajax,但您将其视为同步的。

在执行初始发送调用后的其余代码时,异步调用开始执行其工作。因为代码没有返回任何东西,所以你得到了 undefined。

如果查看 XMLHttpRequest 对象,open 方法中的第三个参数是异步标志。

open("method", "URL"[, asyncFlag[, "userName"[, "password"]]])

将其设置为 true [默认为关闭] 将进行异步调用。将其设置为 false 将使其同步。

使用同步调用的问题是它会锁定用户的浏览器,直到调用返回。这意味着动画 gif 内容、浏览器计时器停止等等。如果服务器需要永远响应,用户就不能做任何事情。

最好的解决方案是避免使用同步调用。使用回调继续代码执行流程。

因此,根据您的编辑,我将使用基本解决方案编辑我的回复

function send(uri, callback)
{
    var xhr = new XMLHttpRequest();
    xhr.open("POST",uri,true);
    xhr.onreadystatechange = function (send){
        if(xhr.readyState == 4){  //You really should check for status here because you can get 400, 500, etc
            callback(xhr.responseText);
            //return 
        }   
    }
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
    xhr.send(null);
}



function myFunction(){

  var myUrl = "foo.php";

  //show a loading message or soemthing
  var someDiv = document.getElementById("loadingMessage");
  someDiv.style.display = "block";

  //Second half of your function that handles what you returned.
  function gotData( value ){
      someDiv.style.display = "none";
      alert(value);
  }

  send(myUrl, gotData);

}

如果你真的想做同步并且你不介意锁定用户的浏览器

function send(uri, callback)
{
    var xhr = new XMLHttpRequest();
    xhr.open("POST",uri,false);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
    xhr.send(null);
    if(xhr.status==200){
        return xhr.responseText;
    }
    else{
        return null;
    }
}

【讨论】:

    【解决方案2】:

    我猜你说的是XMLHTTPRequest.send() 方法,而不是框架的包装器。

    send 不返回任何内容。它将始终返回undefined

    要获得 HTTP 响应,您需要监控 onreadystatechange,正如无数 StackOverflow 答案和互联网教程(例如 this one)所展示的那样。

    【讨论】:

    • @Skizit 那么问题是什么?
    • 它仍然返回未定义。我用函数send send 分配变量返回onreadystatechange 但是当我的代码正在执行时.. responsesend() 可以返回之前返回未定义。如何停止 response 下的代码运行,直到响应被分配发送值?
    【解决方案3】:

    您必须为请求的 readystatechange 事件的响应分配值,如下所示:

    req.onreadystatechange = function(){
     if (req.readyState===4) { // checks if data is already loaded.
        callback(req.responseText,req.status);  //call your callback function with response and status as parameters.           
     }
    };
    

    【讨论】:

      【解决方案4】:

      试试这个:

      function send(uri, callback)
      {
          var xhr = new XMLHttpRequest();
          xhr.open("POST",uri,true);
          xhr.onreadystatechange = function (send){
              if(xhr.readyState == 4 and callback){
                  callback();
              }   
          }
          xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
          xhr.send(null);
      }
      
      send("uri here", function(){
          //whatever needs to be done after request
      })
      

      【讨论】:

      • 如果 send 带参数怎么办?
      • @Skizit:没有好问题我就无法知道答案 :) 尝试新的答案....
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-17
      • 1970-01-01
      • 2016-03-17
      • 1970-01-01
      • 1970-01-01
      • 2012-09-08
      • 1970-01-01
      相关资源
      最近更新 更多