有没有办法将值传递给GM​​_xmlhttprequest?

时间:2009-02-08 18:05:42

标签: javascript asynchronous greasemonkey gm-xmlhttprequest

如下所示:

How can I return a value from GM_xmlhttprequest?

我有一个异步的脚本。我想传递一个值INTO这个函数,以便在调用onload函数时我可以用它来显示在网页中。

我遇到的挑战是,每次将其传递给函数时,此值都会发生变化。

所以,例如,如果我传入'abc','def','xyz'。

我最终会以

结束
xyz
xyz
xyz

而不是

abc
def
xyz

所以,我的问题是,如何将一个值传递给这个函数,以便函数的每次调用都知道完成后要显示什么?

1 个答案:

答案 0 :(得分:5)

您正在寻找closure: -

var urls = {"abc": "http://somehost/aurl",
           "def": "http://somehost/otherurl",
           "ghi": "http://someotherhost/aurl" }

for (var k in urls)
{

    GM_xmlhttpRequest({
        method: 'GET',
        url: urls[k],
        onload: function(text) {
            return  function(xhr) {
                //Do stuff with xhr responseText etc and the text parameter
                alert(text)
            }
        }(k)
    }
}

在每个未完成的请求完成后,这将提醒“abc”,“def”和“ghi”。