[問題] XMLHttpRequest 範例

看板Ajax作者 (as)時間15年前 (2009/12/31 09:21), 編輯推噓0(0011)
留言11則, 2人參與, 最新討論串1/1
小弟爬了之前的文章 照著下面的網址作了一個簡單的程式 https://developer.mozilla.org/En/Using_XMLHttpRequest 結果 xmlhttp.status 總是傳回 0 用 firebug 還看到如下可怕的 error : uncaught exception: [Exception... "Component returned failure code: 0x80004005 (NS_ERROR_FAILURE) [nsIXMLHttpRequest.send]" nsresult: "0x80004005 (NS_ERROR_FAILURE)" location: "JS frame :: http://localhost/test.html :: dumpPage :: line 18" data: no] 懇請各位大大幫忙看一下怎麼回事 謝謝 測試程式如下 : <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "" rel="nofollow">http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html> <head> <title>Dump webpage</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript"> function dumpPage() { document.getElementById('theExample').innerHTML = 'start dump page'; if (window.XMLHttpRequest) { // code for Mozilla, Safari, etc xmlhttp=new XMLHttpRequest(); xmlhttp.onreadystatechange=raw; str = "http://www.mozilla.org/"; xmlhttp.open("GET", str, true); xmlhttp.send(null); } } function raw() { if (xmlhttp.readyState==4) { if (xmlhttp.status==200) { document.getElementById('theExample').innerHTML=xmlhttp.responseText; } } } </script> </head> <body> <div id="theExample">Loading...</div> <br/> <br/> <input type="button" onclick="dumpPage()" value="Dump Page" /> </body> </html> -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 98.234.115.90

12/31 10:12, , 1F
你code中沒有插你看status的code , 你在哪看 status 是 0 ??
12/31 10:12, 1F

12/31 10:13, , 2F
另外正常狀況下 , raw 在一次request 的期間會被調用3-4次
12/31 10:13, 2F

12/31 10:13, , 3F
readyStata==4 跟 status==200
12/31 10:13, 3F

12/31 10:14, , 4F
還有 , 你應該要用一個全域變數來放xmlhttp , 以你的例子來
12/31 10:14, 4F

12/31 10:14, , 5F
講 raw 這個function 中 , xmlhttp 是會有存取scope的問題的
12/31 10:14, 5F

12/31 10:16, , 6F
發現第三行漏字:所以才要判斷 readyState 跟 status
12/31 10:16, 6F

12/31 10:16, , 7F
最後 , 你get的是一個外部網域的網址 , 根據安全性原則
12/31 10:16, 7F

12/31 10:17, , 8F
request 只能 request 與原網頁所在處同網域的內.
12/31 10:17, 8F

12/31 10:17, , 9F
如果有問題就貼有問題的code , 不要貼別人的sample.
12/31 10:17, 9F

12/31 13:08, , 10F
發現問題出在request 只能 request 與原網頁所在處同網域
12/31 13:08, 10F

12/31 13:09, , 11F
謝謝 TonyQ 的詳細解釋
12/31 13:09, 11F
文章代碼(AID): #1BE_o7JJ (Ajax)
文章代碼(AID): #1BE_o7JJ (Ajax)