jquery ajax设置header的两种方式

一、setting参数 headers

$.ajax({  
    headers: {  
        Accept: "application/json; charset=utf-8"  
    },  
    type: "get",  
    success: function (data) {  
    }  
});  

二、beforeSend方法

$("#test").click(function() {  
                $.ajax({  
                    type: "GET",  
                    url: "default.aspx",  
                    beforeSend: function(request) {  
                        request.setRequestHeader("Test", "Chenxizhang");  
                    },  
                    success: function(result) {  
                        alert(result);  
                    }  
                });  
            }); 

转载自:https://blog.youkuaiyun.com/guodengh/article/details/73176549


jQuery中,使用Ajax请求时可以通过`$.ajax()`方法或`$.ajaxSetup()`方法来添加请求头信息。以下是两种常见的方法: ### 方法一:使用`$.ajax()`方法 `$.ajax()`方法允许你在发送请求时通过`headers`选项来添加自定义的头信息。 ```javascript $.ajax({ url: 'your-url', // 请求的URL type: 'GET', // 请求类型 headers: { 'Authorization': 'Bearer your-token', // 自定义头信息 'X-Custom-Header': 'CustomHeaderValue' // 其他自定义头信息 }, success: function(response) { // 请求成功的回调函数 console.log(response); }, error: function(error) { // 请求失败的回调函数 console.error(error); } }); ``` ### 方法二:使用`$.ajaxSetup()`方法 如果你需要在多个Ajax请求中重复使用相同的头信息,可以使用`$.ajaxSetup()`方法进行全局设置。 ```javascript $.ajaxSetup({ headers: { 'Authorization': 'Bearer your-Header': 'CustomHeaderValue' // 其他自定义头信息 } }); // 之后的所有Ajax请求都会自动包含这些头信息 $.ajax({ url: 'your-url', // 请求的URL type: 'GET', // 请求类型 success: function(response) { // 请求成功的回调函数 console.log(response); }, error: function(error) { // 请求失败的回调函数 console.error(error); } }); ``` ### 解释 1. **$.ajax()方法**:通过`headers`选项添加头信息。这种方式适用于单个Ajax请求。 2. **$.ajaxSetup()方法**:通过全局设置添加头信息。这种方式适用于多个Ajax请求,避免重复代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值