variables - 如何从 GM_xmlhttprequest 返回值?

标签 variables greasemonkey global-variables alert 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';
                }
        }
    });

当我添加

alert(infiltrationResult);



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

但是,在该功能退出后,我尝试了相同的警报,但得到:
undefined

任何想法我做错了什么?

最佳答案

请求异步运行。这就是为什么该函数需要一个 onload首先是回调函数。如果是同步的,则 GM_xmlhttpRequest将像普通函数一样简单地返回响应详细信息。

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

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

关于variables - 如何从 GM_xmlhttprequest 返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/525243/

相关文章:

c - 局部变量丢失其值 : selection sort algorithm

javascript - 更改 YouTube 中嵌入的 Flash 对象的来源

javascript - 执行 JavaScript 以呈现用于服务器端缓存的 HTML

JQuery 读取 JSON(全局/局部变量)

python - 我可以获得在 Python 2.7 中引用其他变量的列表吗?

variables - 为什么整数变量大小受到限制(限制为 32/64 位等)?

javascript - 我的 `head` 在哪里?

c# - 如何在 C# 中获得对枚举类型的全局访问权限?

python全局变量问题

Php 阻塞变量声明(w/psql)