修改 JSONP 请求的 HTTP 标头 [英] Modify HTTP Headers for a JSONP request

查看:47
本文介绍了修改 JSONP 请求的 HTTP 标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 jquery 构建对 Twitter 搜索 API 的请求.我正在使用 jsonp,这是跨域请求所需要的.但是,Twitter API 指定您应该为这些请求设置一个唯一的用户代理,如果您不这样做,则会限制您的请求.问题是,我看不到通过 jquery 设置此标头的方法.

I am using jquery to build a request to the Twitter Search API. I am using jsonp, as is needed for cross-domain requests. However, the Twitter API specifies that you should set a unique User-Agent for these requests, and limits your requests if you do not. The problem is, I see no way of setting this header via jquery.

这是我正在使用的代码:

This is the code I am using:

$.ajax({
    url: 'http://search.twitter.com/search.json',
    dataType: 'jsonp',
    type: 'get',
    data: { q: 'twitter' },
    success: function(data) {
        alert(data.results);
    }
});

我尝试过使用 beforeSend 方法,但似乎没有触发此事件.谁能想出解决这个问题的任何方法?

I have tried using the beforeSend method, but it appears that this event is not firing. Can anyone come up with any way of solving this problem?

谢谢.

推荐答案

JSON with Padding 通过向页面添加脚本元素来工作,src 属性指向 Web 服务的 URL.然后,Web 服务返回一个脚本,其中包含包装在回调函数中的数据,该回调函数在脚本完成解析时执行.它不是 JSON(它甚至不必是有效的 JSON,首先),而是纯 JavaScript.

JSON with Padding works by adding a script element to the page, with the src attribute pointing to the URL of the web service. The web service then returns a script containing the data wrapped in a callback function that is executed when the script finishes parsing. It's not so much JSON (it doesn't even have to be valid JSON, for a start) as it is Plain JavaScript.

很遗憾,无法修改为添加到您页面的脚本元素发送的标头.您唯一能做的就是检查检索数据的跨域兼容方法,例如:

There's no way to modify the headers sent for a script element that's added to your page, unfortunately. The only thing you can do is check for a cross-origin compatible method of retrieving data, such as:

  • XMLHttpRequest Level 2 - Chrome, Safari 4+, Firefox 3.5+, Opera

// Is XMLHttpRequest Level 2 supported?
if ("withCredentials" in new XMLHttpRequest()) 

  • XDomainRequest - 用于 IE8、IE 9

  • XDomainRequest - for IE 8, IE 9

    // Is XDomainRequest supported?
    if ("XDomainRequest" in window)

  • 如果这些实现存在并相应地使用它们,那么测试它们是一个好主意,对于不受支持的或更旧的浏览器,回退到标准 JSONP.

    It would be a good idea to test for these implementations if they exist and use them accordingly, falling back to standard JSONP for unsupported or older browsers.

    也有可能(但不太可能,因为它是高调的)Web 服务未设置为允许跨域请求,因此如果请求失败,您可能仍需回退到 JSONP.另请参阅跨域资源共享.

    It's also possible (but unlikely, given that it's high profile) that the web service isn't set up to allow cross-origin requests, so you may still have to fall back to JSONP if the request fails. See also, Cross-Origin Resource Sharing.

    这篇关于修改 JSONP 请求的 HTTP 标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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