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

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

问题描述

我正在使用jquery来构建对Twitter Search API的请求。我正在使用jsonp,这是跨域请求所需要的。但是,Twitter API指定您应为这些请求设置唯一的User-Agent,如果不这样做,则会限制您的请求。问题是,我看不到通过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通过向页面添加脚本元素来工作, 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 - 适用于IE 8,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天全站免登陆