使用 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
Set Headers with jQuery.ajax and JSONP?
提问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 dataType
to 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...
如果我设置dataType
为jsonp
(来自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 src
attribute 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 请求添加自定义标头。