【问题标题】:AJAX Request - get HTTP Code/Response Header for successful requestAJAX 请求 - 获取成功请求的 HTTP 代码/响应标头
【发布时间】:2017-05-22 05:05:46
【问题描述】:

我正在尝试从我的 AJAX 请求中获取 HTTP 响应代码/响应标头。这是我的原始脚本:

$("#callContact1").click(function() {
  $.ajax({
      url: "https://www.server.com?type=makecall",
      data: {},
      type: "GET"
    })
    .then(function(data) {
      $('#ajaxResponse').html(data).show();
    })
    .fail(function(xhr) {
      var httpStatus = (xhr.status);
      var ajaxError = 'There was an requesting the call back. HTTP Status: ' + httpStatus;
      console.log('ajaxError: ' + ajaxError);
      //make alert visible 
      $('#ajaxResponse').html(ajaxError).show();
    })
})

这工作正常。我已对此进行了更新,以尝试获取 HTTP 响应代码/标头并在 console.log 中查看它,但我在那里看不到任何东西。这是我更新的脚本:

$("#callContact1").click(function() {
  console.log('starting call back request');
  $.ajax({
      url: "https://www.server.com?type=makecall",
      data: {},
      type: "GET"
    })
    .then(function(data) {
      $('#ajaxResponse').html(data).show();
      var httpStatus = (data.status);
      var httpResponseCode = (data.getAllResponseHeaders);
      console.log('httpStatus: ' + httpStatus);
      console.log('httpResponseCode: ' + httpResponseCode);
    })
    .fail(function(xhr) {
      var httpStatus = (xhr.status);
      var ajaxError = 'There was an requesting the call back. HTTP Status: ' + httpStatus;
      console.log('ajaxError: ' + ajaxError);
      //make alert visible 
      $('#ajaxResponse').html(ajaxError).show();
    })
})

但我在控制台中没有得到任何东西(尽管请求已成功执行)。我还注意到更新脚本第二行的输出也没有出现在控制台中。

【问题讨论】:

  • 清除浏览器历史记录后再试
  • 控制台中有关于 CORS 的信息吗?还是 Access-Control-* 标头?
  • 我通过浏览器重新启动,现在在控制台中看到了条目,但我得到的是“未定义”值而不是预期值:httpStatus: undefined httpResponseCode: undefined

标签: javascript jquery ajax


【解决方案1】:

将上面的代码修改为

.then(function(data,status,xhr) {
      $('#ajaxResponse').html(data).show();
      var httpStatus = status;
      var httpResponseCode = (xhr.status);
      console.log('httpStatus: ' + httpStatus);
      console.log('httpResponseCode: ' + httpResponseCode);
    })

【讨论】:

    【解决方案2】:

    您可以在 jQuery 的 jQuery.ajax() 文档中找到

    https://api.jquery.com/jQuery.ajax#jqXHR

    你可以使用 .done() 和 .fail() 或者使用 .then() 两者结合,使用两个回调函数作为参数,第一个代表成功,第二个代表失败。

    所以,你可以像这样使用 smt:

    .then(function(data, status, xhr) {
        $('#ajaxResponse').html(data).show();
        var httpStatus = status;
        var httpResponseCode = (xhr.status);
        console.log('httpStatus: ' + httpStatus);
        console.log('httpResponseCode: ' + httpResponseCode);
    }, function(data, status, xhr) {
        var ajaxError = 'There was an requesting the call back. HTTP Status: ' + status;
        console.log('ajaxError: ' + ajaxError); //make alert visible 
        $('#ajaxResponse').html(ajaxError).show();
    
    })
    

    【讨论】:

      最近更新 更多