GreaseMonkey:GM_xmlhttpRequest返回值到调用函数 [英] GreaseMonkey: GM_xmlhttpRequest return value to calling function

查看:176
本文介绍了GreaseMonkey:GM_xmlhttpRequest返回值到调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经把这个弄乱了好几个小时,然后我把头发拔了出来.如何从myFunction返回var a,以将其设置为var b,然后在警报消息中显示b的值?谢谢! :)

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆