jquery , ajax,get或post时,带上headers
在jQuery的ajax()
方法中,可以使用headers
选项来设置HTTP请求头。以下是一些示例:
使用GET请求:
$.ajax({
url: 'https://example.com/api/data',
type: 'GET',
headers: {
'Authorization': 'Bearer YOUR_TOKEN_HERE',
// 更多自定义headers
},
success: function(result) {
console.log(result);
},
error: function(error) {
console.error(error);
}
});
使用POST请求:
$.ajax({
url: 'https://example.com/api/data',
type: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_TOKEN_HERE',
// 更多自定义headers
},
data: JSON.stringify({
key1: 'value1',
key2: 'value2'
}),
success: function(result) {
console.log(result);
},
error: function(error) {
console.error(error);
}
});
在上述代码中,我们创建了一个包含'Authorization'和(对于POST请求)'Content-Type'头部的请求。你可以根据需要添加更多的请求头。