如何添加回调到AJAX变量赋值赋值、回调、变量、AJAX

2023-09-10 14:43:55 作者:你是一只死在我心里的狗。

我有一个变量的反响这是通过一个AJAX功能发送分配()。当我做任务...

的反响=发送();

发送之前响应返回并给我回一个未定义如何添加一个回调到prevent这种情况的发生?

编辑:什么我问一个澄清。

它仍然返回undefined。我分配的功能变量发送发送回报的onreadystatechange然而,当我的code正在执行..响应返回发送之前为未定义()可以返回。如何从响应到运行停止响应下的code已被分配发送值?

EDIT2:

下面code是我的发送功能...

 函数发送(URI)
{
    VAR XHR =新XMLHtt prequest();
    xhr.open(POST,URI,真正的);
    xhr.onreadystatechange =功能(发送){
        如果(xhr.readyState == 4){
            返回xhr.responseText;
        }
    }
    xhr.setRequestHeader(内容类型,应用程序/ x-WWW的形式urlen codeD;字符集= UTF-8);
    xhr.send(空);
}
 

解决方案

正在以异步方式使用Ajax,但是你对待它是同步的。

异步调用熄灭而在code初始发送调用后剩下的执行来完成其工作。你得到不确定的,因为code不返回任何东西。

怎么得到这个ajax得到的值 我在外面定义了一个变量,可是值没传进去,获取的都是空值

如果你看一下XMLHtt prequest对象,在打开的方法的第三个参数是异步的标志。

 打开(法,URL[,asyncFlag [username的[密码]]])
 

设置为true [默认都不放过]将异步调用。它设置为false将使其同步。

使用同步调用的问题是它锁定了用户的浏览器,直到该呼叫被返回。这意味着GIF动画的东西,浏览器计时器停止,等等。如果服务器需要永远响应,用户无法做任何事情。

最好的解决办法是避免使用同步调用。使用回调继续code的执行流程。

因此​​,根据您的编辑,我将编辑我用碱性溶液反应

 函数发送(URI,回调)
{
    VAR XHR =新XMLHtt prequest();
    xhr.open(POST,URI,真正的);
    xhr.onreadystatechange =功能(发送){
        如果(xhr.readyState == 4){//你真的应该检查状态这里,因为你可以得到400,500,等
            回调(xhr.responseText);
            //返回
        }
    }
    xhr.setRequestHeader(内容类型,应用程序/ x-WWW的形式urlen codeD;字符集= UTF-8);
    xhr.send(空);
}



功能myFunction的(){

  VAR myUrl =foo.php;

  //显示加载信息或soemthing
  变种someDiv =的document.getElementById(loadingMessage);
  someDiv.style.display =块;

  //你的函数来处理你回来什么的下半年。
  功能gotData(值){
      someDiv.style.display =无;
      警报(值);
  }

  发送(myUrl,gotData);

}
 

如果你真的想这样做同步的,你不介意锁定用户浏览器

 函数发送(URI,回调)
{
    VAR XHR =新XMLHtt prequest();
    xhr.open(POST,URI,假);
    xhr.setRequestHeader(内容类型,应用程序/ x-WWW的形式urlen codeD;字符集= UTF-8);
    xhr.send(空);
    如果(xhr.status == 200){
        返回xhr.responseText;
    }
    其他{
        返回null;
    }
}
 

I've got a variable responce which is assigned via an AJAX function send(). When I make the assignment...

responce = send();

response returns before send does giving me back an undefined how can I add a callback to prevent this from happening?

EDIT: a clarification on what I'm asking..

It's still returning undefined. I'm assigning the variable with the function send send returns onreadystatechange however when my code is executing.. response returns as undefined before send() can return. How do I stop the code under response from running on till response has been assigned sends value?

EDIT2:

The following code is my send function...

 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);
}

解决方案

You are using Ajax in a asynchronous manner, but you are treating it to be synchronous.

Asynchronous calls goes off to do its job while the rest of the code after the initial send call executes. You are getting undefined because the code is not returning anything.

If you look at the XMLHttpRequest object, the 3rd argument in the open method is the asynchronous flag.

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

Setting it to true [default is left off] will make an asynchronous call. Setting it to false will make it synchronous.

The problem with using synchronous calls is it locks up the user's browser until the call is returned. That means animated gifs stuff, browser timers stop, and so on. If the server takes forever to respond, the user can not do anything.

The best solution is to avoid using synchronous calls. Use the call back to continue the code execution flow.

So based on your edit, I will edit my response with a basic solution

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);

}

If you really want to do synchronous and you do not mind locking up a user's browser

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;
    }
}