js ajax设置和获取自定义header信息的方法总结

  • Post author:
  • Post category:其他


目录

1、js ajax 设置自定义header


回到顶部


1.1 方法一:

$.ajax({
    type: "POST",
    url: "Handler1.ashx",
    contentType: "application/x-www-form-urlencoded",
    beforeSend: function (request) {
        request.setRequestHeader("token1", "Chenxizhang");
    },
    success: function (data) {
		//your code
    }
});


回到顶部


1.2 方法二:

$.ajax({
    headers: {
        "testheader": "test"
    },
    type: "POST",
    url: "Handler1.ashx",
    contentType: "application/x-www-form-urlencoded",
    success: function (data) {
    	//your code
    }
});

2、js ajax 获取请求返回的response的header信息

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
		*/
        
    }
});

3、js ajax 跨域请求的情况下获取自定义的header信息

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");
}