IE8 中的 jQuery ajax 调用错误

标签 jquery ajax internet-explorer-8

我有一个基于 jQuery 构建的相当简单的 ajax 调用。它在 IE9、最新版 Firefox 和最新版 Chrome 中完美运行(所以我非常确定 AJAX 调用发布到的页面没有问题),但在 IE8 上(未尝试过 IE7)它会失败。

jQuery 代码是:

$('.to-step-2').click(function(){
  var d = new Date();
  var roomShape;
  blnError = false;
  $.ajax({
    url: '/base/RoomBuilder/GetRoomShape.aspx?_='+d.getTime(),
    async: false,
    type: 'post',
    cache: false,
    dataType: 'html',
    success: function(data){
      if(data.substring(0,5) == 'Error'){
        alert('Please select a room shape to continue');
        blnError = true;
      }else{
        roomShape = data;
      }
    },
    error: function(jqXHR, textStatus, errorThrown){
      alert('Error 6: jqXHR = ' + jqXHR + '\ntextStatus = ' + textStatus + '\nerrorThrown = ' + errorThrown);
      blnError = true;
    }
  });    
  if (blnError == true){
    return false;
  }

仅在 IE8 中抛出的错误是:

Error 6: jqXHR = [object Object]
textStatus = error
errorThrown = Length Required

我看过其他一些关于类似事情的帖子,但添加时间戳和缓存:false以防止缓存似乎是相当常见的解决方案,但仍然不适合我:(

有人能明白为什么会发生这种情况并提出修复建议吗?

最佳答案

您将获得 411 response来自您的服务:

411 Length Required

The server refuses to accept the request without a defined Content- Length. The client MAY repeat the request if it adds a valid Content-Length header field containing the length of the message-body in the request message.

这是因为如果没有数据,jQuery 在发布时不会设置内容长度 header 。这是发布到 IIS 时的安全要求:

The underlying issue is that most installations of IIS6+ require a content-length be provided with all POST requests, even if there is no content (POST data).

The content-length for a request with no data should be 0, but jQuery doesn’t set that header automatically unless there is a data parameter. Since ASP.NET AJAX’s JSON serialized services require a POST request, this becomes a stumbling block for read-only requests.

(Quoted from from http://encosia.com/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/)

简单地将数据参数设置为空对象似乎是最简单的解决方法:

$.ajax({
url: '/base/RoomBuilder/GetRoomShape.aspx?_='+d.getTime(),
async: false,
type: 'post',
cache: false,
data: "{}",
dataType: 'html',
success: function(data){
  if(data.substring(0,5) == 'Error'){
    alert('Please select a room shape to continue');
    blnError = true;
  }else{
    roomShape = data;
  }
}

关于IE8 中的 jQuery ajax 调用错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9032549/

相关文章:

javascript - 在没有垂直滚动条的html中设置所有div

javascript - 在 Jquery/Javascript 中检查一个 URL

javascript - 通过 ajax 刷新 WooCommerce 迷你购物车

ajax - 在浏览器中捕获服务器端 ajax 处理错误

javascript - 如何在 IE8 中停止事件传播

php - 单击按钮后我想显示表格并打开新窗口

javascript - 在嵌套循环中设置间隔

javascript - Ajax 成功数据返回完整的 HTML 页面

javascript - Hammer.js jQUery 插件在 IE7/8 中不起作用

html - IE8 支持 Bootstrap3 + LESS