javascript - 检测链接是否是 javascript/jQuery 中的下载

标签 javascript php jquery download cross-browser

我正在开发一个 PHP 应用程序,该应用程序可能需要几秒钟才能加载下一页。为了防止用户在下一页加载时垃圾点击按钮(并让他们知道页面正在加载),我实现了一个覆盖该页面的页面加载微调器:

// Assume all internal links start with "http://www.example.com"
$('a[href*="http://www.example.com"]').on("click", function () {
  var href = $(this).attr("href");
  if (!href || href[0] === "#") {
    location.hash = href;// set that hash
    return;
  } else {
    location = href;
    $(".loading-spinner").fadeIn(100, function () {
        setTimeout(function(){ $(".loading-spinner").fadeOut(200); }, 10000); // 10 second loading maximum
    });
  }
  return false;
});

如果链接开始文件下载,我希望在检测到下载后立即淡出.loading-spinner

是否有某种方法可以检测链接是否触发了下载与使用 javascript/jQuery 加载页面,还是我需要专门识别所有下载链接(使用特殊类等)?

最佳答案

向 URL 发起 AJAX 请求并使用 getResponseHeader 获取内容类型功能:

$.get(url, function (response, status, xhr) {
  if (xhr.getResponseHeader("content-type").indexOf("text") > -1)
    // Text based stuff.
  else
    // Download based stuff. (eg., application/pdf, etc.)
});

更多信息:

The XMLHttpRequest.getResponseHeader() method returns the string containing the text of the specified header, or null if either the response has not yet been received or the header doesn't exist in the response. If there are multiple response headers with the same name, then their values are returned as a single concatenated string, where each value is separated from the previous one by a pair of comma and space. The getResponseHeader() method returns the value as a UTF byte squence.

关于javascript - 检测链接是否是 javascript/jQuery 中的下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37383600/

相关文章:

javascript - 下划线过滤器嵌套对象数组

php - 如何使用 MySQL、PHP 等创建动态日历

php - Laravel 5 leftJoin on belongsTo 关系

javascript - 如何在 JavaScript 中创建对象集合并在另一个对象中赋值?

javascript - 如何使用ajax获取文本区域数据(文本区域中的Html文件)并且我需要将数据发送到Php? Ajax 不发送我的文本区域数据?

javascript - 如何将框阴影值从 RGB 值转换为 HEX 值

javascript - 使用 superagent-cache 缓存不同参数的 HTTP 响应

javascript - 循环生成JSON

javascript - 使用 Canvas 引擎和平铺 map 编辑器获取 "Uncaught TypeError: Cannot read property ' firstgid' of undefined"

php - 将 HTML 放入 JSON