I need to communicate between Javascript and PHP (I use jQuery for AJAX), but the output of the PHP script may contain binary data. That's why I use bin2hex() and json_encode() on PHP side.
How do I convert the hexadecimal string in binary string, with JavaScript?
解决方案
JavaScript doesn't have support for binary data. Nevertheless you can emulate this with regular strings.
var hex = "375771", // ASCII HEX: 37="7", 57="W", 71="q"
bytes = [],
str;
for(var i=0; i< hex.length-1; i+=2){
bytes.push(parseInt(hex.substr(i, 2), 16));
}
str = String.fromCharCode.apply(String, bytes);
alert(str); // 7Wq