2

As indicated here:

How can I return a value from GM_xmlhttprequest?

I have a script that is asynchronous. I would like to pass a value INTO this function so that when the onload function is called I can use it to display in the web page.

The challenge I'm having is that this value will change each time I pass it into the function.

So, for instance if I passed in 'abc', 'def', 'xyz'.

I would end up with

xyz
xyz
xyz

instead of

abc
def
xyz

So, my question is, how would I pass a value into this function so that each call of the function knows what to display when it's done?

Community
  • 1
  • 1
GeoffreyF67
  • 11,061
  • 11
  • 46
  • 56

1 Answers1

5

You are looking for a 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)
    }
}

This will alert "abc", "def" and "ghi" after each outstanding request completes.

Community
  • 1
  • 1
AnthonyWJones
  • 187,081
  • 35
  • 232
  • 306
  • What's the syntax for multiple parameters? Do you just add a comma after the k? e.g. }(k,x) – Doug Dec 27 '13 at 17:27
  • Also, I was unable to edit a correction, but there is a missing `)`. I think it goes right after the `}` in the line of code just above the last line. – PMM Apr 14 '18 at 00:42
  • Could someone explain how the `}(k)` near the end works ... for example, is `(k)` how the `GM_xmlhttpRequest`'s `onload` passes the value of `k` back to the `for` loop? I am also confused by the `return function(xhr){alert(text)}`. Specifically, I don't understand the need for the function; e.g. why isn't that line of code simply `alert(text)`? – PMM Apr 14 '18 at 00:46