我正在尝试读取与MyFile.html位于同一域的二进制文件MyFile.xxx。使用JQuery我只是尝试在MyFile.xxx中显示一个包含字符数的警报,并打印每个字符的数字表示。但是,根据浏览器的不同,我会得到不同的结果:
谷歌浏览器:我正确显示33,并显示正确的整数 Firefox:警报显示“未定义”,不会打印整数。 IE9:警告显示“1”,不会打印整数。
有什么想法吗?感谢
MyFile.html
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$.get('/MyFile.xxx', function(a){
var l=a.length,x=[l];
alert(l);
for(i=0;i<l;i++){
x[i]=a[i].charCodeAt(0);
document.write(x[i]);
document.write("<br>");
}
});
</script>
</head>
<body>
</body>
</html>
答案 0 :(得分:1)
试试这个:
$.ajax( "/MyFile.xxx", {
dataType: "text",
beforeSend: function( xhr ) {
xhr.overrideMimeType( "text/plain; charset=x-user-defined");
},
success: function( data ) {
var len = data.length,
str = "";
for( var i = 0; i < len; ++i ) {
var byte = data.charCodeAt(i) & 0xFF;
str += byte + " ";
}
document.body.innerHTML = str;
}
});
演示:http://jsfiddle.net/SXgfu/(显示åöä
的UTF-8字节)
请注意,IE9不支持此功能。它不支持获取响应的原始字节的任何其他方式。
如果您使用的是PHP,则可以使用此解决方法进行IE:
$.get("/base64encoder.php?file=MyFile.xxx", function(data) {
data = decode64(data);
var len = data.length,
str = "";
for (var i = 0; i < len; ++i) {
var byte = data.charCodeAt(i) & 0xFF;
str += byte + " ";
}
document.body.innerHTML = str;
}, "text");
base64encoder.php
类似于:
<?php
echo base64_encode(file_get_contents( $_GET['file'] ));
记得来清理以上内容,否则这是一个巨大的安全漏洞
和decode64
(src http://ntt.cc/2008/01/19/base64-encoder-decoder-with-javascript.html):
var keyStr = "ABCDEFGHIJKLMNOP" +
"QRSTUVWXYZabcdef" +
"ghijklmnopqrstuv" +
"wxyz0123456789+/" +
"=";
function decode64(input) {
var output = "";
var chr1, chr2, chr3 = "";
var enc1, enc2, enc3, enc4 = "";
var i = 0;
// remove all characters that are not A-Z, a-z, 0-9, +, /, or =
var base64test = /[^A-Za-z0-9\+\/\=]/g;
if (base64test.exec(input)) {
alert("There were invalid base64 characters in the input text.\n" + "Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='\n" + "Expect errors in decoding.");
}
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
do {
enc1 = keyStr.indexOf(input.charAt(i++));
enc2 = keyStr.indexOf(input.charAt(i++));
enc3 = keyStr.indexOf(input.charAt(i++));
enc4 = keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
chr1 = chr2 = chr3 = "";
enc1 = enc2 = enc3 = enc4 = "";
} while (i < input.length);
return output;
}