ajax成功处理程序中的数据编码不同 [英] Data encoding is different in ajax success handler

查看:152
本文介绍了ajax成功处理程序中的数据编码不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用AJAX从服务器下载excel文件。但下载的数据与实际数据不同

I am using AJAX to download the excel file from server. But the downloaded data is different from actual data

实际数据为橙色背景。收到的数据是黄色的背景。

Actual data is with orange background. Received data is in yellow background.

从差异文件看,它们使用的是不同的编码格式。所以excel抛出错误的文件是不正确的格式。

From the difference file, it looks like they are using different encoding formats. So excel throws error that the file is not in correct format.

    $.ajax({
        url: exporting.action,
        headers: { "Authorization": "Basic " + btoa("key : " + key) },
        type: "post",
        responseType: "arraybuffer",
        success: function (res, status, obj) {                
            var blob = new Blob([str2ab(res)], { type: obj.getResponseHeader('Content-Type') });                
            var objectUrl = URL.createObjectURL(blob);
            window.open(objectUrl);
        },
        data: { 'Model': JSON.stringify(modelClone) }
    });

请帮助解决这个

推荐答案

编码的麻烦是导致jQuery没有响应arraybuffer而是字符串。字符串是JavaScript UTF-16和字符串中的二进制数据造成麻烦的麻烦。我建议你使用本机AJAX而不是jQuery。代码是类似的,浏览器支持与浏览器支持的blob和对象URLS相同。您使用的是

The trouble with "encoding" is caused that jQuery did not response arraybuffer but string. Strings are in JavaScript UTF-16 and binary data in string cause trouble next to trouble. I recommend you to use native AJAX instead of jQuery. Code is similar and browser support is the same as the browser support of blobs and object URLS what you use.

var xhr = new XMLHttpRequest();
xhr.open("POST", exporting.action);
xhr.setRequestHeader("Authorization", "Basic " + btoa("key : " + key));
xhr.responseType = "arraybuffer";
xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && xhr.status == 200) {
        var blob = new Blob([xhr.response], { type: xhr.getResponseHeader('Content-Type') });
        var objectUrl = URL.createObjectURL(blob);
        window.open(objectUrl);
    }
}.bind(this);
xhr.send({ 'Model': JSON.stringify(modelClone)});

这篇关于ajax成功处理程序中的数据编码不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆