代码之家  ›  专栏  ›  技术社区  ›  Dan D.

修改JSONP请求的HTTP头

  •  25
  • Dan D.  · 技术社区  · 15 年前

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

    这是我使用的代码:

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

    我已尝试使用beforesend方法,但似乎此事件未激发。有人能想出解决这个问题的办法吗?

    谢谢。

    2 回复  |  直到 12 年前
        1
  •  55
  •   Andy E    15 年前

    带有填充的JSON通过向页面添加脚本元素来工作,使用 SRC 指向Web服务的URL的属性。然后,Web服务返回一个脚本,其中包含包装在回调函数中的数据,该回调函数在脚本完成解析时执行。它不像普通的javascript那样简单(一开始它甚至不需要是有效的JSON)。

    不幸的是,无法修改为添加到页面中的脚本元素发送的头。您唯一能做的就是检查跨源兼容的数据检索方法,例如:

    • 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

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

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

    Web服务不允许跨源请求也是可能的(但不太可能,因为它具有很高的知名度),因此如果请求失败,您可能仍然需要返回到JSONP。也见 Cross-Origin Resource Sharing .

        2
  •  0
  •   Azr    12 年前

    试试这个:

    // OAuth configurations   
        var config = {
          'client_id': 'xxxxxx.apps.googleusercontent.com',
          'scope': 'https://www.google.com/m8/feeds/contacts/default/full'          
        };
    
    gapi.auth.authorize(config, function(data) {
          // login complete - now get token
          var token = gapi.auth.getToken();
          token.alt = 'json';
          // retrieve contacts
          jQuery.ajax({
            url: 'https://www.google.com/m8/feeds/contacts/default/full/?max-results=999999',
            dataType: 'jsonp',
            data: token,
            success: function(data) { successGmail(data); }
          });
        });
    

    我在那里找到的: https://groups.google.com/d/msg/google-api-javascript-client/GuFxPzqQ9-0/hZpo041UaH4J

    推荐文章