Ajax 请求在 Safari、Chrome 中不起作用

Ajax request not working in Safari, Chrome

本文关键字:Chrome 不起作用 Safari 请求 Ajax      更新时间:2023-09-26

我有一个 ajax 请求,当单击链接下载文件时触发。 称为服务器端页面,该页面使用访问者下载的客户 ID 和文件名更新数据库。 使用 Jquery 1.5.1。 这是链接 html:

<a href="/downloads/whatever.zip" class="software">click here to download</a>

ajax 请求编写如下,并包含一个函数,用于通知 ajax 请求中是否存在错误:

$(document).ready(function() {
  //function to alert an error message if request is unsuccessful
  function ajaxError(request, type, errorThrown)
  {
  var message = "There was an error with the AJAX request.'n";
  switch (type) {
      case 'timeout':
          message += "The request timed out.";
          break;
      case 'notmodified':
          message += "The request was not modified but was not retrieved from the cache.";
          break;
      case 'parseerror':
          message += "XML/Json format is bad.";
          break;
      default:
          message += "HTTP Error (" + request.status + " " + request.statusText + ").";
  }
  message += "'n";  
  alert(message);
  }

$('a.software').click(function() {  
//get the path of the link, and just the file name to be stored in the database
var filePath = $(this).attr("href");
var partsArray = filePath.split('/');
var theFileName = partsArray[partsArray.length-1];

  $.ajax({
     type: "POST",
     url: "/validate/softwareDownloadedCustomer.asp?custID=<%=custID%>&fileName=" + theFileName,
     success: function(msg) {
      alert("Success");
     },
     error: ajaxError
    });
  }); 
});

服务器端代码不是问题,当仅由另一个页面而不是 ajax 请求调用时,它会按预期工作。 奇怪的是,ajax请求在Firefox和IE中有效,但在Chrome和Safari中不起作用。 在 IE 中,将发出"成功"消息警报并更新数据库。 在Firefox,Chrome和Safari中,我收到警报的错误消息如下:

There was an error with the AJAX request.
HTTP Error (0 error)

即使在 Firefox 中收到错误消息,它也会更新数据库。 在 chrome 和 safari 中,会收到错误消息,但不会更新任何内容。

我尝试在我的 ajax 调用中使用以下设置,它似乎在任何浏览器中都没有区别:

contentType: "application/json; charset=utf-8",
dataType: "json", 'data' 

我缺少什么才能让它在 Safari 和 Chrome 中工作?

我实际上找到了导致问题的原因 - 这是由于 ajax 请求被激活下载文件的链接中断。ajax 请求是通过单击链接触发的。错误消息的请求状态为 0,这意味着链接操作显然正在中断 ajax 请求。由于某种原因,显然在IE中请求没有中断,但是它在Firefox,safari和chrome中,因此出现错误消息。 我在这里找到了相关信息:链接。

在测试了 ajax 请求以简单的按钮单击而不是链接触发后,我知道情况就是这种情况。 它在所有浏览器中都成功运行,只需单击按钮即可触发时没有错误消息。

解决方法不是使用 AJAX,而是将用户发送到记录单击的服务器端页面,然后重定向到相应的下载链接。

您的 Ajax 请求使用 POST,但不发布任何数据。您正在传递的数据是通过您的 URL 请求参数进行的。

尝试将 ajax 类型更改为 GET

type: "GET",      
url: "/validate/softwareDownloadedCustomer.asp?custID=<%=custID%>&fileName=" + theFileName, 

或通过发布数据传递参数

var dataToPost = 'custID=<%=custID%>&fileName=' + theFileName;
type: "POST",      
url: "/validate/softwareDownloadedCustomer.asp", 
data : dataToPost,