我有一个 XMLHttpRequest 将大量数据插入 MySQL 数据库,需要 5-10 秒。这是请求的代码:
function sendRequest(url, params, divToChange)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest)
{
var httpRequest = new XMLHttpRequest();
}
else // code for IE6, IE5
{
var httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
// Stage 3 - open the request and prepare variables for the PHP method being
activated on server side//
httpRequest.open("POST", url, true);
//Set request headers for POST command//
httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpRequest.setRequestHeader("Content-length", params.length);
httpRequest.setRequestHeader("Connection", "close");
httpRequest.onreadystatechange=function()
{
if(httpRequest.readyState==3)
{
document.getElementById(divToChange).innerHTML='please wait';
}
if(httpRequest.readyState==4 && httpRequest.status==200)
{
document.getElementById(divToChange).innerHTML=httpRequest.responseText;
}
}
httpRequest.send(params); // Stage 4 - sending the request to the server//
//end when the server will responde we will execute the
"document.getElementById("txtHint").innerHTML=xmlhttp.responseText;" //
}
//Calling the request with this function//
function createEventList()
{
var url = "grid-update_event_list.php";
var params = "firstLoad=1";
//Create the httpRequest and send it to the server//
sendRequest(url,params, "eventsList");
}
这是在我的 html 中定义的以获取响应文本:
<p>Events List Status: <b id='eventsList'> </b></p>
我无法理解浏览器中的两种行为:
1-“请稍候”文本永远不会显示在浏览器上。当我添加了一个alert(httpRequest.readyState)
来测试正在发生的事情时,我得到了预期的“3”弹出窗口,但我在readyState==3
它转到readyState==4
. 似乎它们同时发生。我确实看到了在 of 中返回的httpRequest.responseText;
文本readyState==4
。
2-发送请求后我无法导航到另一个页面,当前页面是响应式的(我可以更改组合框)但是当我尝试导航到另一个链接时,浏览器等待到 readyState==4,然后它才会继续链接。我也无法理解,因为请求定义为asynchronous = true
.
我做错了什么导致这两种行为吗?谢谢。