如何让 jquery.Ajax 与“throw 1;”一起使用<不要作恶>”在 json 响应前面?不要作恶>
Google 将 Unparsable Cuft 返回到 json 响应,如下所示:
throw 1; <dont be evil> { foo: bar}
- 我当前的 Web 应用程序使用 jQuery.Ajax 来检索 JSON 数据。应如何修改它们以消耗有效数据?
这是相关演示
Google returns Unparsable Cuft to the json response like this:
throw 1; <dont be evil> { foo: bar}
- My current web applications use jQuery.Ajax to retrieve JSON data. How should they be modified to consume valid data?
Here is a relevant demo
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可能应该从响应中删除开头部分:
更新:
为了使重写在每个 Ajax 调用中可用,您还可以在 jQuery 中注册一个全局 Ajax 转换器:
您仍然需要指定定义的
dataType
在请求选项中。更新2:
如果您需要调整现有的调用以自动进行响应清理,您可以修补 jQuery 的
ajax
实现,以便在某些情况下自动使用您的转换器:请注意,必须在加载 jQuery 之后和进行第一个 Ajax 调用之前包含此重新定义。您可能还需要考虑
$.ajax
也可以 在没有单独url 的情况下调用< /code> 参数
...
You should probably remove the beginning part from the response:
UPDATE:
To make the re-writing available in every Ajax call you could also register a global Ajax Converter in jQuery:
You will still need to specify your defined
dataType
in the request options.UPDATE 2:
If you need to tweak your existing calls to do the response cleanup automatically, you could patch jQuery's
ajax
implementation to automatically use your converter in certain situations:
Note that this redefinition has to included after loading jQuery and before the first Ajax call is made. You may also need to consider that
$.ajax
can also be called without a separateurl
parameter...我利用
$.ajaxSetup
方法更简单地实现了这一点:http: //api.jquery.com/jQuery.ajaxSetup/
并使用转换器:
它的作用是利用每个 ajax 调用并即时进行必要的转换/替换。它本质上是将您的对象读取为“文本”,替换不可解析的内容,并吐出一个新的 json 对象。
效果很好。我设置了它然后忘记它,它不会干扰任何未受污染的 json。
I achieved this a little simpler taking advantage of the
$.ajaxSetup
method:http://api.jquery.com/jQuery.ajaxSetup/
and using converters:
What this does is tap into every ajax call and makes the necessary conversion/replacement on the fly. It essentially takes your object which it reads as "text", replaces the unparseable cruft, and spits out a new json object.
Works great. I set it and forget it and it won't interfere with any non-tainted json.