日期: 2020-06-22 17:45:59
本文实例讲述了js 使用ajax设置和获取自定义header信息的方法。分享给大家供大家参考,具体如下:
$.ajax({ type: "POST", url: "Handler1.ashx", contentType: "application/x-www-form-urlencoded", beforeSend: function (request) { request.setRequestHeader("token1", "Chenxizhang"); }, success: function (data) { //your code } });
$.ajax({ headers: { "testheader": "test" }, type: "POST", url: "Handler1.ashx", contentType: "application/x-www-form-urlencoded", success: function (data) { //your code } });
ajax请求完成,会返回xhr(XMLHTTPRequest)对象,这里面会包含返回的头信息,可以通过getResponseHeader(key)和getAllResponseHeaders()获取header信息;
$.ajax({ type: "POST", url: "Handler1.ashx", contentType: "application/x-www-form-urlencoded", success: function (data) { //your code }, complete: function (xhr, data) { /* 获取相关Http Response header getResponseHeader(key):获取指定头信息 getAllResponseHeaders():获取全部可默认可获取的头信息 */ var date=xhr.getResponseHeader('Date');// 服务器端时间 //获取服务端自定义的header信息 var stoken = xhr.getResponseHeader('servertoken'); var list = xhr.getAllResponseHeaders(); console.log(list); /* date: Fri, 12 Jul 2019 12:41:00 GMT content-encoding: gzip server: Microsoft-IIS/10.0 x-aspnet-version: 4.0.30319 x-powered-by: ASP.NET vary: Accept-Encoding content-type: text/plain; charset=utf-8 servertoken: test1 cache-control: private content-length: 129 */ } });
JS AJAX 跨域请求的时候是不能设置自定义的header信息的,但是是可以在response中获取到服务端自定义的header信息,前提是服务端设置了Access-Control-Expose-Headers;
下面是 ASP.NET 的服务端示例:
public void ProcessRequest(HttpContext context) { context.Response.AddHeader("Access-Control-Allow-Origin", "*"); context.Response.AddHeader("Access-Control-Allow-Headers", "*"); context.Response.AddHeader("Access-Control-Allow-Methods", "*"); //自定义header信息 context.Response.AddHeader("servertoken", "test"); context.Response.AddHeader("Access-Control-Expose-Headers", "servertoken"); context.Response.ContentType = "text/plain"; context.Response.Write("Hello World"); }
更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《JavaScript中ajax操作技巧总结》、《JavaScript错误与调试技巧总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》及《JavaScript数学运算用法总结》
希望本文所述对大家JavaScript程序设计有所帮助。