GreaseMonkey:GM_xmlhttpRequest返回值到调用函数 [英] GreaseMonkey: GM_xmlhttpRequest return value to calling function
问题描述
function myFunction(arg)
{
var a;
GM_xmlhttpRequest({
method:"GET",
url:"http://site.com/arg?" + arg,
headers:{
"User-Agent":"monkeyagent",
"Accept":"text/monkey,text/xml",
},
onload:function(details) {
a = details.responseText;
}
});
return a;
}
b = myFunction("blabla");
alert(b);
当我尝试时,它仅返回空白消息.
您不能像这样返回a
,因为GM_xmlhttpRequest
是异步操作的.
myFunction
返回后,onload函数将触发很长时间.您要使用a
进行的所有操作都必须通过onload函数中调用的函数来完成.
Greasemonkey just 从版本0.9.9开始增加了对同步模式的支持.如果需要的话,您可以在这里此处下载版本0.9.10的预发行版. .
但是,您会很聪明地学习异步处理这种事情.您将获得一个更快,响应更快的UI,而不是挂起"和冻结".应对各种现实编程情况是一个好主意.
ive been messing round with this for hours and im pulling my hair out at it. How do I return var a from myFunction to allow it to be set as var b which and then display the value of b in the alert message? Thanks! :)
function myFunction(arg)
{
var a;
GM_xmlhttpRequest({
method:"GET",
url:"http://site.com/arg?" + arg,
headers:{
"User-Agent":"monkeyagent",
"Accept":"text/monkey,text/xml",
},
onload:function(details) {
a = details.responseText;
}
});
return a;
}
b = myFunction("blabla");
alert(b);
When I tried it returned just a blank message.
You can't return a
like that because GM_xmlhttpRequest
operates asynchronously.
The onload function will fire long after myFunction
has returned. Anything that you want to do with a
will have to be done from functions called within the onload function.
Greasemonkey just added support for synchronous mode, starting with version 0.9.9. If you must, you can download the prerelease of version 0.9.10, here.
However, you would be smart to learn to handle this kind of thing asynchronously. You will get a faster, more responsive UI instead of "hangs" and "freezes". It's a good concept to grok for all manner of real-life programming situations.
这篇关于GreaseMonkey:GM_xmlhttpRequest返回值到调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!