我在这里有此代码:

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';
                }
        }
    });

当我添加时

警报(渗透率);

分配后,我正确地看到了字符串。

但是,在函数退出后,我尝试了相同的警报,我得到了:

undefined

有什么想法我做错了什么?

有帮助吗?

解决方案

该请求异步运行。那是 为什么 该功能采用 onload 首先回调功能。如果是同步的,那就 GM_xmlhttpRequest 只需像普通功能一样返回响应细节。

在等待返回请求时,请致电后的代码 GM_xmlhttpRequest 继续运行。您的脚本正确识别 infiltrationResult 由于请求尚未完成,因此不确定。

如果您需要做更多的事情,而不仅仅是在请求返回时分配变量,那么请在 onload 打回来。

其他提示

尝试这个:

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);
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top