【问题标题】:jQuery: Content type header is not setjQuery:未设置内容类型标头
【发布时间】:2013-07-21 03:45:20
【问题描述】:

我正在尝试发送跨域 ajax GET 请求

$(document).ready(function(){
    $.ajax
      ({
        type: "GET",
        url: "url",
        cache: false,
        contentType: "application/x-www-form-urlencoded",
        dataType: "jsonp",
        beforeSend: function (xhr){ 
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
            xhr.setRequestHeader('Authorization', make_base_auth("login", "pwd")); 
        },
        success: function (data, success){
            console.log("success", arguments); 
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log("error", arguments);
        },
        complete: function(jqxhr, textStatus) {
          console.log("complete", arguments);
        }
    });
});

服务器只接受 application/x-www-form-urlencoded 数据。 发送请求后,我收到 415 状态的响应(不支持的媒体类型) 当我在 firebug 中检查标头时,根本看不到 Content-Type 标头。

GET /url?callback=jsonp1374315852923&_=1374315854258 HTTP/1.1
Host: hostname
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:22.0) Gecko/20100101 Firefox/22.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://refferer
Cookie: JSESSIONID=1DCD5D9EB35FEF083C7EAF8F7EA25D54; ltime=1374315850; lid=30000379384174; SESS826f62d511330ecdaa9034d04e399c65=qj2jcempp4osi2hc00lq1jnkp1; AA_SESS=2c-30f9987cd946; AA_UID=0fe8965d05c37706a5bfbec88629ed68
Authorization: Basic YWthdml0YTpQNlBhdQ==
Connection: keep-alive

非常感谢您的 cmets!

【问题讨论】:

  • jsonp 并不是真正的 ajax,它会在 DOM 中插入一个脚本标签,仅此而已,所以除非您联系的服务支持这一点,否则它不会通过设置标题来神奇地工作。跨度>
  • "跨域请求和dataType:"jsonp"请求不支持同步操作。" docu

标签: jquery cross-domain jsonp


【解决方案1】:

您正在使用 JSONP 作为您的数据类型。 JSONP 使 jQuery 简单地将脚本标签插入到您的文档中,然后将其拉入,就好像它是一个普通的浏览器请求一样。因此,您无法在其上设置标题。

如果您没有使用 JSONP 的特定需求(您使用的是同一个域),那么请改用 JSON。如果您跨域发出请求,请考虑使用 CORS(在旧版浏览器中可能无法使用)。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-03-28
  • 2013-04-18
  • 2021-05-23
  • 2013-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多