如果AJAX REST API成功或失败,如何在成功或错误回调中访问请求标头?

时间:2019-12-18 14:21:03

标签: javascript jquery ajax rest api

例如,我有:

$.ajax({
    type: 'POST',
    url: 'https://jsonplaceholder.typicode.com/todos',
    data: { name: 'random name' },
    headers: { 'x-my-custom-header': 'XYZ' },
    success: function(successResp) {
      console.log(successResp);
    },
    error: function(errorResp){
        console.log(errorResp);
    }
});

如何在成功或错误回调中从请求标头访问“ x-my-custom-header”?

3 个答案:

答案 0 :(得分:1)

如果您没有在context设置中明确包含$.ajax()属性,那么在您的“成功”等中,处理程序this将引用设置对象本身。因此,this.headers将为您提供其他标题属性。

More information at MDN.

答案 1 :(得分:1)

将标头存储在变量中。

let customHeader = { 'x-my-custom-header': 'XYZ' };
$.ajax({
type: 'POST',
url: 'https://jsonplaceholder.typicode.com/todos',
data: { name: 'random name' },
headers: customHeader,
success: function(successResp) {
  console.log(customHeader);
},
error: function(errorResp){
    console.log(customHeader);
}});

答案 2 :(得分:-1)

您可以尝试此操作,因为如果从成功回调中请求作为第三个参数,则request对象是可访问的:

$.ajax({
type: 'POST',
url:'https://jsonplaceholder.typicode.com/todos',
data: { name: 'random name' },
headers: { 'x-my-custom-header': 'XYZ' },
success: function(data, textStatus, request){
    alert(request.getResponseHeader('some_header'));
},
error: function (request, textStatus, errorThrown) {
    alert(request.getResponseHeader('some_header'));
}

});

有关更多详细信息,请访问:https://api.jquery.com/jQuery.ajax/

相关问题