問題描述
這是我從 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 始終返回零狀態.
XMLHttpRequest always returns a zero status.
Firefox 的錯誤控制臺中沒有顯示任何內容.
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 和文件位于同一目錄中.如果你嘗試這個,你還需要一個文件 SBL_PROBES.htm,它的內容是無關緊要的.
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 語句中使用函數.該函數在readystate變為4時執行.
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);
您的舊代碼執行了異步調用,并僅使用 alert 語句繼續.此時 T 為空.
Your old code did a asynchronous call and continued just with the alert Statement. T was empty at this time.
好的,我會稍微解釋一下整個過程是如何工作的:
Ok, I'll explain a little bit how this whole thing works:
首先我們定義兩個回調函數,我們稍后在請求中調用它們,命名為handleResponse 和handleStateChange.
First we define two callback functions, which we call later in the request, named handleResponse and handleStateChange.
然后我們創建一個對象,它代表 XMLHttpRequest
Afterwards we create a Object, which represents the XMLHttpRequest
var xmlhttp=new XMLHttpRequest();
這會產生如下的對象(簡化):
This results in an Object as follows (simplyfied):
XMLHttpRequest { status=0, readyState=0, multipart=false, onreadystatechange=handleEvent()}
使用 open(...) 函數調用,您可以為請求設置參數:
With the open(...) function call you set parameters for the request:
xmlhttp.open("GET","SBL_PROBES.htm",true);
這意味著,執行異步 GET 請求來獲取頁面 SBL_PROBES.htm然后調用 send(...) 函數來觸發請求本身.
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.
我們為onreadystatechange注冊了一個回調函數,可以想象,這實際上是一個eventHandler.每次狀態改變時都會調用這個函數.(這就像你在表單中注冊一個回調函數到一個onKeyUp事件一樣,每次你的key上升時都會觸發這個回調:))
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 :) )
對您的問題感興趣的唯一情況是狀態 4.因此,僅在狀態 4 中調用 handleRequest 回調函數.此時您的 Request 實際上有一個結果,還有一個狀態.(狀態表示您的網絡服務器返回狀態代碼 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 背后的全部魔力,但應該為您提供一個簡化的概述,即幕后實際發生的事情.請務必在網絡服務器上進行測試,不要使用 file://進行測試.
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.
如果您需要更多詳細信息,請告訴我.
If you need more in detail info, just let me know.
這篇關于XMLHttpRequest 異步不起作用,總是返回狀態 0的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!