1

我试图让GM_xmlhttpRequest调用的行为同步,但我不能得到它的工作像我期望:同步GM_xmlhttpRequest异步操作?

function myFunction (arg) { 
    var a; 

    GM_xmlhttpRequest ({ 
     method:   "GET", 
     url:   "http://example.com/sample/url", 
     synchronous: true, 

     onload: function (details) { 
      a = details.responseText; 
     } 
    }); 

    return a; 
} 
b = myFunction(); 
alert (b); 

我从来没有得到任何东西回来b这里;它是未定义的。有没有我在这里失踪的一些步骤?
我使用Greasemonkey的v0.9.13和Firefox的v9.0.1。

+0

是的......我不得不重构我的代码,因为这个“bug” – w35l3y 2012-01-09 01:49:44

+0

不要使用同步请求。使用如[此处](http://stackoverflow.com/q/32338061/)或[这里](http://stackoverflow.com/a/5192249/331508)所示的异步方法,等等。 – 2015-09-16 15:25:14

回答

4

刚在Google上偶然发现了这个话题。

同步GM_xmlhttpRequest返回结果,而不是在onload回调中执行它。

所以这将是正确的:

var details = GM_xmlhttpRequest({ 
    method:"GET", 
    url:"http://site.com/sample/url", 
    synchronous: true 
}); 
a = details.responseText; 

您创建VAR“一”在开始的时候,从来没有填满它,并将其返回。因此,它是不确定的。