Javascript Ajax发送函数不会';开火?
每当我运行这个文件时,代码都会一直运行到发送函数触发的点,然后只有当我直接在它后面有一个警报函数,如果我取出警报(“发送”),它才会触发;然后它用Javascript Ajax发送函数不会';开火?,javascript,ajax,Javascript,Ajax,每当我运行这个文件时,代码都会一直运行到发送函数触发的点,然后只有当我直接在它后面有一个警报函数,如果我取出警报(“发送”),它才会触发;然后它用ServerReadyyStateis:1进行回复 可能是什么问题?有人请帮忙,我已经在我的本地机器和我的个人服务器上试过了,得到了同样的结果。非常感谢您的帮助 守则: /** * @author d */ var xhr; function getPlants(xhr) { try { xhr = new XMLHttpReques
ServerReadyyState
is:1进行回复
可能是什么问题?有人请帮忙,我已经在我的本地机器和我的个人服务器上试过了,得到了同样的结果。非常感谢您的帮助
守则:
/**
* @author d
*/
var xhr;
function getPlants(xhr) {
try {
xhr = new XMLHttpRequest();
} catch (microsoft) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
xhr = false;
alert("ajax not supported");
}
}
}
xhr.open("GET", "db_interactions.php", true);
xhr.send(null);
alert("sent"); //the send function only works if this alert functions is here
if (xhr.readyState == 4) {
return xhr.responseText;
} else {
alert("Server ReadyState is:" + xhr.readyState);
xhr.abort();
//getPlants(xhr);
}
}
AJAX是异步的。您不能在之后立即检查就绪状态 正确的设计模式是为AJAX调用分配一个函数,以便在就绪状态更改时运行
xhr.onreadystatechange = function () { alert('It changed!') }
在该函数中,您需要检查状态是否为4。如果是这样,您就可以处理输出了。如果没有,则什么也不做,因为在就绪状态为4之前,该函数将被调用几次。AJAX是异步的。您不能在之后立即检查就绪状态 正确的设计模式是为AJAX调用分配一个函数,以便在就绪状态更改时运行
xhr.onreadystatechange = function () { alert('It changed!') }
在该函数中,您需要检查状态是否为4。如果是这样,您就可以处理输出了。否则,什么也不做,因为在就绪状态为4之前,该函数将被调用几次。请求需要一些时间。添加警报()时,代码将停止,直到用户单击“确定”。因此,当您删除它时,请求将被发送并立即检查。导致未完成的请求 将代码更改为以下内容时:
xhr.onreadystatechange=state_change
xhr.send(null);
function state_change() {
if(xhr.readyState==4) {
return xhr.responseText;
} else {
alert("Server ReadyState is:"+xhr.readyState);
}
}
像本例中的state\u change这样的特定函数在每次状态更改时都会被调用。因此,您可以等待请求完成或出现错误代码。请求需要一些时间。添加警报()时,代码将停止,直到用户单击“确定”。因此,当您删除它时,请求将被发送并立即检查。导致未完成的请求 将代码更改为以下内容时:
xhr.onreadystatechange=state_change
xhr.send(null);
function state_change() {
if(xhr.readyState==4) {
return xhr.responseText;
} else {
alert("Server ReadyState is:"+xhr.readyState);
}
}
像本例中的state\u change这样的特定函数在每次状态更改时都会被调用。因此,您可以等待请求完成或出现错误代码