开发者

How save responseText returns from GM_xmlhttpRequest?

开发者 https://www.devze.com 2023-03-31 00:38 出处:网络
I tried: GM_xmlhttpRequest({ method: \"GET\", url: \"...\", onload: function(response) { r = response.responseText;

I tried:

GM_xmlhttpRequest({
    method: "GET",
    url: "...",
    onload: function(response) {
        r = response.responseText;

    }});
alert(r); //undefi开发者_Python百科ned 

How do this?


Why this is happening

By default, ajax requests using XMLHTTPRequest are asynchronous. This means that the call to method returns immediately and the main execution continues while the request proceeds in the background. When the request completes, the callback method will be invoked with the results of the request. Thus, your alert is executed before the (asynchronous) request ever completes.

Solution 1: Callbacks

You haven't provided context as to why you'd need the response text synchronously so it's possible you could rewrite your code to use callbacks and continue using the asynchronous behaviour - this is usually good practice.

Solution 2: Force synchronous requests

However, if find that you absolutely must make requests synchronously, you'll find that you can request that the ajax request be made synchronously. With Greasemonkey, you should use the option synchronous: true when invoking GM_xmlhttpRequest, as documented here. Note that the docs say that

Be careful: The entire Firefox UI will be locked and frozen until the request completes. In this mode, more data will be available in the return value.

With XHR objects in the browser, you'd achieve the same results by passing false as the second parameter to XMLHTTPRequest#open.

If you're working with an older version of Greasemonkey, the answers to this SO question might prove useful: How to make synchronous AJAX calls in greasemonkey?

0

精彩评论

暂无评论...
验证码 换一张
取 消