在greasemonkey用户脚本中的jQuery.getJSON [英] jQuery.getJSON inside a greasemonkey user script

查看:138
本文介绍了在greasemonkey用户脚本中的jQuery.getJSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个用于生成跨域AJAX请求的用户脚本。

I am attempting to write a user script that makes a cross domain AJAX request.

我在我的脚本中使用@require包含了jQuery,一切似乎都在工作直到我尝试运行jQuery.getJSON。

I have included jQuery inside my script using @require and everything seems to be working fine up until the point where I try to run jQuery.getJSON.

我访问的API支持jsonp,但是我一直收到一条错误,指出jsonp123456789没有定义。

The API I am accessing supports jsonp, however I keep getting an error stating jsonp123456789 is not defined.

从我能够收集到的,这是由于jQuery将jsonp响应直接写入页面的头部,然后变为沙盒。一旦发生这种情况,jQuery就无法再访问回调,导致它被取消定义。 (我不是100%就这种情况,但似乎对我而言)。

From what I have been able to gather this is due to jQuery writing the jsonp response directly into the head of the page, which then becomes sandboxed. Once that has occured jQuery can no longer access the callback resulting in it being undefined. (I'm not 100% on this being the case, but it seems likely to me).

有什么方法可以解决这个问题吗?有人建议我在unsafeWindow中声明回调函数,但我不确定如何做到这一点并且没有设法让它工作。

Is there any way to work around this? It has been suggested I declare the callback function inside unsafeWindow but I'm unsure how to do this and haven't managed to get it to work.

推荐答案

如果jQuery在内部使用 GM_xmlhttpRequest 会不会很好,这样你就可以拥有jQuery方法的所有便利和Greasemonkey的跨站点功能?正如mahemoff指出的那样,Greasemonkey可以让你在不依赖JSONP的情况下提出请求并遇到你所面临的回调问题,但你必须自己处理JSON内容。

Wouldn't it be nice if jQuery used GM_xmlhttpRequest internally so that you could have all the convenience of the jQuery methods and the cross-site functionality of Greasemonkey? As mahemoff points out, Greasemonkey could let you make the request without relying on JSONP and running into the callback problem you're facing, but you'll have to deal with the JSON contents yourself.

我们已经编写了一个可以做到这一点的库: Greasemonkey / jQuery XHR桥。如果你的用户脚本中有 @require 那个脚本,那么所有 $。get $。 getJSON $。发布等.jQuery调用将跨站点工作,而不依赖于JSONP等技术。

We've written a library that will do just that: the Greasemonkey/jQuery XHR bridge. If you @require that script in your userscript, then all $.get and $.getJSON and $.post, etc. jQuery calls will work cross-site without relying on techniques like JSONP.

因此,如果您使用此网桥并只是从您的网址中删除?callback =?,那么您的jQuery代码应该是工作没有修改。 这篇博文提供了一步一步的演练。如果有人对网桥插件有任何问题,意见,错误报告或建议,请告诉我。

So if you use this bridge and simply remove the ?callback=? from your URL, your jQuery code should work without modification. This blog post provides a step-by-step walkthrough. If anyone has any questions, comments, bug reports or suggestions about the bridge plugin, please let me know.

这篇关于在greasemonkey用户脚本中的jQuery.getJSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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