如何从GM_xmlhttprequest返回值?

Geo*_*F67 5 variables alert greasemonkey global-variables undefined

我在这里有这个代码:

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';
                }
        }
    });
Run Code Online (Sandbox Code Playgroud)

当我添加

警报(infiltrationResult);

在分配之后,我正确地看到了字符串.

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

undefined
Run Code Online (Sandbox Code Playgroud)

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

Rob*_*edy 8

请求以异步方式运行.这就是该函数首先采用onload回调函数的原因.如果它是同步的,那么GM_xmlhttpRequest只需像普通函数一样返回响应细节.

在等待请求返回时,调用后的代码GM_xmlhttpRequest继续运行.您的脚本正确识别infiltrationResult未定义的脚本,因为请求尚未完成.

如果您需要做的不仅仅是在请求返回时分配变量,那么在onload回调中执行此操作.