使用 jQuery.ajax 和 JSONP 设置标题?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3073287/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:49:11  来源:igfitidea点击:

Set Headers with jQuery.ajax and JSONP?

jqueryajaxcross-domainheader

提问by Lance Pollard

I am trying to access google docs with jQuery. Here's what I have so far:

我正在尝试使用 jQuery 访问 google 文档。这是我到目前为止所拥有的:

var token = "my-auth-token";
$.ajax({
  url: "http://docs.google.com/feeds/documents/private/full?max-results=1&alt=json",
  dataType: 'jsonp',
  beforeSend: function(xhr) {
    xhr.setRequestHeader("Authorization", "GoogleLogin auth=" + token);
  },
  success: function(data, textStatus, XMLHttpRequest) {
  },
  error: function(XMLHttpRequest, textStatus, errorThrown) {
  }
});

It doesn't allow me to set headers if I set the dataTypeto jsonp(from Make Cross Domain Ajax Requests with jQuery). If I leave out jsonp, I can't make the cross-domain request. If I use jQuery.getJSON, I can't pass in any headers...

如果我设置dataTypejsonp(来自Make Cross Domain Ajax Requests with jQuery),它不允许我设置标头。如果我遗漏了jsonp,我将无法进行跨域请求。如果我使用jQuery.getJSON,则无法传入任何标题...

Is there any way to define custom headers when making a cross-domain ajax request (in jQuery)?

在进行跨域 ajax 请求(在 jQuery 中)时,有没有办法定义自定义标头?

回答by SLaks

This is not possible.

这不可能。

A JSONP request works by creating a <script>element with its srcattribute set to the request URL.
You cannot add custom headers to the HTTP request sent by a <script>element.

JSONP 请求的工作方式是创建一个<script>元素,并将其src属性设置为请求 URL。
您不能向<script>元素发送的 HTTP 请求添加自定义标头。