JS Ajax实现文件下载功能

实现文件流转blob对象下载

download("http://.....exportData", {name: "小明", age: 18});

function download(url, data) {
    var xhr = new XMLHttpRequest(); //ajax的技术核心是XMLHttpRequest对象
    xhr.open("post", url);
    xhr.setRequestHeader("Content-Type","application/json;charset=UTF-8"); //设置请求头
    xhr.responseType = "blob"; //返回类型blob
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            if (xhr.status >= 200 && xhr.status < 300) {
                var data = xhr.response;
                var defaultFileName = xhr.getResponseHeader("Content-Disposition").split(";")[1].split("filename=")[1]; //从响应头中获取文件名
                var filename = decodeURI(defaultFileName); //解码
                //判断浏览器类型
                const uA = window.navigator.userAgent;
                con

你可能感兴趣的:(javascript,ajax)