2009-02-08 362 views
4

我有這樣的代碼在這裏:如何從GM_xmlhttprequest返回值?

var infiltrationResult; 

while(thisOption) { 
    var trNode = document.createElement('tr'); 
    var tdNode = document.createElement('td'); 
    var hrefNode = document.createElement('a'); 

    infPlanetID = thisOption.getAttribute('value'); 

    var myURL = "http://www.hyperiums.com/servlet/Planetinf?securitylevel=90&newinfiltr=New+infiltration&planetid=" + PlanetID + "&infplanetid=" + infPlanetID; 

    GM_xmlhttpRequest({ 
     method: 'GET', 
     url: myURL, 
     headers: { 
      'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey', 
      'Accept': 'application/atom+xml,application/xml,text/xml', 
     }, 
     onload: function(responseDetails) { 
       if (responseDetails.responseText.match(/<b>Invalid order<\/td><\/tr><tr><td><BR><center><font color=#AAAA77 face=verdana,arial size=2>The target planet is blocking all infiltrations[\s\S]<BR><BR>/im)) { 
        // Successful match 
        infiltrationResult = 'Invalid Order'; 
       } else { 
        // Match attempt failed 
        infiltrationResult = 'Infiltration Successfully Created'; 
       } 
     } 
    }); 

當我添加

警報(infiltrationResult);

它被分配後,我正確地看到字符串。

但是,函數退出後,我嘗試同樣的警告,我得到:

undefined 

任何想法我做錯了嗎?

回答

7

該請求異步運行。那是爲什麼這個函數首先需要一個onload回調函數。如果它是同步的,那麼GM_xmlhttpRequest只會像普通函數那樣返回響應細節。

在等待請求返回時,GM_xmlhttpRequest調用後的代碼繼續運行。您的腳本正確識別infiltrationResult未定義,因爲請求尚未完成。

如果在請求返回時您需要做的不僅僅是分配變量,那麼請在onload回調中執行該操作。

+0

你是絕對正確的。把那個結果變成這個函數的代碼移動到這個函數中就可以解決所有問題 謝謝! G-Man – GeoffreyF67 2009-02-08 06:27:26

1

試試這個:

var infiltrationResult; 

while(thisOption) { 
    var trNode = document.createElement('tr'); 
    var tdNode = document.createElement('td'); 
    var hrefNode = document.createElement('a'); 

    infPlanetID = thisOption.getAttribute('value'); 

    var myURL = "http://www.hyperiums.com/servlet/Planetinf?securitylevel=90&newinfiltr=New+infiltration&planetid=" + PlanetID + "&infplanetid=" + infPlanetID; 

    GM_xmlhttpRequest({ 
     method: 'GET', 
     url: myURL, 
     headers: { 
      'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey', 
      'Accept': 'application/atom+xml,application/xml,text/xml', 
     }, 
     onload: function(responseDetails) { 
         if (responseDetails.responseText.match(/<b>Invalid order<\/td><\/tr><tr><td><BR><center><font color=#AAAA77 face=verdana,arial size=2>The target planet is blocking all infiltrations[\s\S]<BR><BR>/im)) { 
           // Successful match 
           infiltrationResult = 'Invalid Order'; 
         } else { 
           // Match attempt failed 
           infiltrationResult = 'Infiltration Successfully Created'; 
         } 
         sentback(infiltrationResult);//Sent it when it loads only 
     } 
    }); 

function sentback(x){ 
    alert(x); 
}