我有一个变量responce
,它是通过AJAX函数send()
分配的。当我完成任务时......
responce = send();
响应返回确实给了我undefined
如何添加回调来防止这种情况发生?
编辑:澄清我在问什么......
它还在返回undefined。我正在使用函数send send返回onreadystatechange来赋值变量,但是当我的代码正在执行时...在send()返回之前,响应返回为undefined。如何在响应中停止响应,直到响应已分配发送值?
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);
}
答案 0 :(得分:2)
我认为你在讨论的是XMLHTTPRequest.send()
方法,而不是框架的包装器。
send
不会返回任何内容。它将始终返回undefined
。
要获得HTTP响应,您需要监控onreadystatechange
,无数StackOverflow答案和互联网教程(例如this one)演示。
答案 1 :(得分:2)
您正在以异步方式使用Ajax,但您将其视为同步。
在执行初始发送调用之后的其余代码中,异步调用将完成其工作。您未定义,因为代码没有返回任何内容。
如果查看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 :(得分:0)
试试这个:
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
})
答案 3 :(得分:0)
您必须在请求的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.
}
};