javascript 如何像ajax一样在jQuery.load中传递标题?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20067027/
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
how to pass headers in jQuery.load like ajax?
提问by Rocky Andra
I've been stuck from this issue in couple of days. I want to send some headers data in jQuery.load(). It seems that jQuery.load never send the headers, like ajax. Can somebody explain how to, or Is it necessary? Btw, sory my bad English.
这几天我一直被这个问题困扰。我想在 jQuery.load() 中发送一些标题数据。似乎 jQuery.load 从不发送标头,如 ajax。有人可以解释如何,还是有必要?顺便说一句,对不起,我的英语不好。
This is the syntax :
这是语法:
$loadingBay.load(href, settings.data, function (data, status) {
prep(status === 'error' ? $tag(div, 'Error').html(settings.xhrError) : $(this).contents());
});
Many Thanks
非常感谢
采纳答案by Prabhuram
You can use beforeSend
option in jquery ajax
, like as follows :
您可以使用beforeSend
选项 in jquery ajax
,如下所示:
$.ajax({
url: "http://localhost/restTest",
data: { uname: "asdf" },
type: "GET",
beforeSend: function(xhr){xhr.setRequestHeader('X-TOKEN', 'xxxxx');},
success: function() { alert('Success!' + authHeader); }
});
or can also use headers
like,
或者也可以使用headers
像,
$.ajax({
url: "http://localhost/restTest",
data: { uname: "asdf" },
type: "GET",
headers:{ "X-TOKEN": 'xxxxx'},
success: function() { alert('Success!' + authHeader); }
});
回答by MD. Sahib Bin Mahboob
You can not pass headers data to $.load()
, but you can set default setup using $.ajaxSetup()
like this :
您不能将标头数据传递给$.load()
,但您可以使用以下方法设置默认设置$.ajaxSetup()
:
$.ajaxSetup({
'headers':{
'header1':'value1',
'header2':'value2',
}
}
);
//give the load call here
$('selector').load('url',function(){
//do things
})
Disclaimer From jquery doc:
来自jquery 文档的免责声明:
Its use is not recommended.
不推荐使用它。
The best way is do the is thing using $.ajax()
:
最好的方法是使用以下方法$.ajax()
:
$.ajax({
url: "test.html",
headers : {header1 : "header1"}
}).done(function(data) {
$('selector').html(data);
});