2010-11-08 69 views
1

我正在使用以下腳本通過Firefox擴展UI加載一些數據。nsIXMLHttpRequest只執行至readyState 1

var req = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(); 
var www = "http://localhost/view?url=http://google.com"; 
req.open('GET', www, true); 

if (req.readyState){ 
    alert(req.readyState); 
} 

它告誡只是1
腳本顯示正在啓用與嚴格的JavaScript錯誤控制檯沒有錯誤。

+0

可能與您使用alert()有關。試試只用window.dump代替 – MatrixFrog 2010-11-08 16:03:45

回答

0

有兩個問題與您的代碼:

  • 你忘了打電話給req.send(null)。該請求僅在您致電send()時執行。
  • 您正在執行異步請求,因爲您指定the third parameter for open()true。這意味着在您請求readyState時,請求仍會執行。你應該使用一個readystatechange聽衆像這樣:

    req.onreadystatechange = function (aEvt) { 
        if (req.readyState == 4) { 
         if(req.status == 200) 
          dump(req.responseText); 
         else 
          dump("Error loading page\n"); 
        } 
    }; 
    

我建議採取看看the documentation on Using XMLHttpRequest,其中包含了上面和其他幾個人的例子。

+0

啊!我犯了多少愚蠢的錯誤。 :(我怎麼能忘記readystatechange,現在它看起來如此明顯,爲什麼它只是警報1. thnx :) – 2010-11-15 07:09:12

+0

沒問題。往往很容易忽視某些事情,並採取新的觀點有所幫助。它解決了你的問題嗎? – 2010-11-15 10:16:47

+0

是的,它完美的工作。珍珠樹是你的插件嗎? :? – 2010-11-15 13:33:58