如何使用js或jQuery向Ajax请求添加自定义HTTP头?有人知道如何使用JavaScript或jQuery添加或创建自定义HTTP头吗?
3 回答

aluckdog
TA贡献1847条经验 获得超7个赞
headers
// Request with custom header$.ajax({ url: 'foo/bar', headers: { 'x-my-custom-header': 'some value' }});
$.ajaxSetup()
:
$.ajaxSetup({ headers: { 'x-my-custom-header': 'some value' }});// Sends your custom header$.ajax({ url: 'foo/bar' }); // Overwrites the default header with a new header$.ajax({ url: 'foo/bar', headers: { 'x-some-other-header': 'some value' } });
beforeSend
$.ajaxSetup()
:
$.ajaxSetup({ beforeSend: function(xhr) { xhr.setRequestHeader('x-my-custom-header', 'some value'); }});// Sends your custom header$.ajax({ url: 'foo/bar' }); // Sends both custom headers$.ajax({ url: 'foo/bar', headers: { 'x-some-other-header': 'some value' } });
编辑(更多信息):ajaxSetup
beforeSend
ajaxSetup

回首忆惘然
TA贡献1847条经验 获得超11个赞
或者,如果您想为以后的每个请求发送自定义标头,则可以使用以下方法:
$.ajaxSetup({ headers: { "CustomHeader": "myValue" }});
这样,未来的每个Ajax请求都将包含自定义标头,除非被请求的选项显式覆盖。

跃然一笑
TA贡献1826条经验 获得超6个赞
function xhrToSend(){ // Attempt to creat the XHR2 object var xhr; try{ xhr = new XMLHttpRequest(); }catch (e){ try{ xhr = new XDomainRequest(); } catch (e){ try{ xhr = new ActiveXObject('Msxml2.XMLHTTP'); }catch (e){ try{ xhr = new ActiveXObject('Microsoft.XMLHTTP'); }catch (e){ statusField('\nYour browser is not' + ' compatible with XHR2'); } } } } xhr.open('POST', 'startStopResume.aspx', true); xhr.setRequestHeader("chunk", numberOfBLObsSent + 1); xhr.onreadystatechange = function (e) { if (xhr.readyState == 4 && xhr.status == 200) { receivedChunks++; } }; xhr.send(chunk); numberOfBLObsSent++;};
添加回答
举报
0/150
提交
取消