問題描述
這是我從 w3schools 拼湊的 XMLHttpRequest 示例
Here's a sample XMLHttpRequest I cobbled together from w3schools
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var T="nothing";
xmlhttp=new XMLHttpRequest();
xmlhttp.overrideMimeType('text/plain'); // don't sc
xmlhttp.onreadystatechange=function()
{
alert ("rdystate: " + xmlhttp.readyState);
alert ("status: " + xmlhttp.status);
alert ("Text: " + xmlhttp.statusText);
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
T = xmlhttp.responseText;
}
}
xmlhttp.open("GET","SBL_PROBES.htm",true);
xmlhttp.send(null);
//T = xmlhttp.responseText;
alert(T);
}
</script>
</head>
<body>
<h2>Using the XMLHttpRequest object</h2>
<div id="myDiv"></div>
<button type="button" onclick="loadXMLDoc()">CHange Content</button>
</body>
</html>
XMLHttpRequest 始終返回零狀態(tài).
XMLHttpRequest always returns a zero status.
Firefox 的錯(cuò)誤控制臺中沒有顯示任何內(nèi)容.
Nothing shows up in Firefox's error console.
如果我通過更改行將請求更改為同步請求
If I change the request to synchronous one by changing the line
xmlhttp.open("GET","SBL_PROBES.htm",true);
到
xmlhttp.open("GET","SBL_PROBES.htm",false);
并取消注釋該行
//T = xmlhttp.responseText;
返回請求文件的文本.
HTM 和文件位于同一目錄中.如果你嘗試這個(gè),你還需要一個(gè)文件 SBL_PROBES.htm,它的內(nèi)容是無關(guān)緊要的.
The HTM and the file reside in the same directory. If you try this you will need a file SBL_PROBES.htm there also, it's contents are irrelevant.
我使用的是 Firefox 3.6.22.
I'm using Firefox 3.6.22.
這可能是跨域問題嗎?如果是這樣,為什么它作為同步請求工作?
Could this be a cross domain problem? If so, why does it work as a synchronous request?
推薦答案
您可以在 if 語句中使用函數(shù).該函數(shù)在readystate變?yōu)?時(shí)執(zhí)行.
You can use a function inside the if statement. This function is executed when readystate changes to 4.
var handleResponse = function (status, response) {
alert(response)
}
var handleStateChange = function () {
switch (xmlhttp.readyState) {
case 0 : // UNINITIALIZED
case 1 : // LOADING
case 2 : // LOADED
case 3 : // INTERACTIVE
break;
case 4 : // COMPLETED
handleResponse(xmlhttp.status, xmlhttp.responseText);
break;
default: alert("error");
}
}
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=handleStateChange;
xmlhttp.open("GET","SBL_PROBES.htm",true);
xmlhttp.send(null);
您的舊代碼執(zhí)行了異步調(diào)用,并僅使用 alert 語句繼續(xù).此時(shí) T 為空.
Your old code did a asynchronous call and continued just with the alert Statement. T was empty at this time.
好的,我會稍微解釋一下整個(gè)過程是如何工作的:
Ok, I'll explain a little bit how this whole thing works:
首先我們定義兩個(gè)回調(diào)函數(shù),我們稍后在請求中調(diào)用它們,命名為handleResponse 和handleStateChange.
First we define two callback functions, which we call later in the request, named handleResponse and handleStateChange.
然后我們創(chuàng)建一個(gè)對象,它代表 XMLHttpRequest
Afterwards we create a Object, which represents the XMLHttpRequest
var xmlhttp=new XMLHttpRequest();
這會產(chǎn)生如下的對象(簡化):
This results in an Object as follows (simplyfied):
XMLHttpRequest { status=0, readyState=0, multipart=false, onreadystatechange=handleEvent()}
使用 open(...) 函數(shù)調(diào)用,您可以為請求設(shè)置參數(shù):
With the open(...) function call you set parameters for the request:
xmlhttp.open("GET","SBL_PROBES.htm",true);
這意味著,執(zhí)行異步 GET 請求來獲取頁面 SBL_PROBES.htm然后調(diào)用 send(...) 函數(shù)來觸發(fā)請求本身.
This means, do a asynchronous GET Request to fetch the Page SBL_PROBES.htm Then the send(...) function is called which fires the request itself.
我們?yōu)閛nreadystatechange注冊了一個(gè)回調(diào)函數(shù),可以想象,這實(shí)際上是一個(gè)eventHandler.每次狀態(tài)改變時(shí)都會調(diào)用這個(gè)函數(shù).(這就像你在表單中注冊一個(gè)回調(diào)函數(shù)到一個(gè)onKeyUp事件一樣,每次你的key上升時(shí)都會觸發(fā)這個(gè)回調(diào):))
We registered a callback function for the onreadystatechange, as you can imagine, this is actually an eventHandler. Each time the state changes this function is called. (It is the same as if you register a callback function to an onKeyUp Event in a form, this callback is triggered each time your key goes up :) )
對您的問題感興趣的唯一情況是狀態(tài) 4.因此,僅在狀態(tài) 4 中調(diào)用 handleRequest 回調(diào)函數(shù).此時(shí)您的 Request 實(shí)際上有一個(gè)結(jié)果,還有一個(gè)狀態(tài).(狀態(tài)表示您的網(wǎng)絡(luò)服務(wù)器返回狀態(tài)代碼 200=ok、404=not found 等)
The only case which is of interest for your problem is state 4. Therefor the handleRequest callback function is called only in state 4. At this time you Request has actually a result, and further a status. (Status means your webserver returned a status code 200=ok, 404=not found etc.)
這并不是 ajax 背后的全部魔力,但應(yīng)該為您提供一個(gè)簡化的概述,即幕后實(shí)際發(fā)生的事情.請務(wù)必在網(wǎng)絡(luò)服務(wù)器上進(jìn)行測試,不要使用 file://進(jìn)行測試.
That is not all the magic which is behind the ajax stuff, but should give you a simplified overview, what is actually happening behind the scenes. It is important that you test this on a webserver, do not use file:// for testing.
如果您需要更多詳細(xì)信息,請告訴我.
If you need more in detail info, just let me know.
這篇關(guān)于XMLHttpRequest 異步不起作用,總是返回狀態(tài) 0的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!