来自 php 的 echo char(128) 及以上不起作用 [英] echo char(128) and above from php does not work
问题描述
我有一个响应两个字符的服务器端 process.php 脚本:
I have a server side process.php script that echos two chars:
echo chr(127);
echo chr(128);
在客户端,我有一个 java 脚本(在 UTF-8 编码的 html 页面中运行),它发布到 php 脚本并期待响应:
On the client side, I have a java script (running in an html page with UTF-8 encoding) that posts to the php script and expects a response:
const xhr = new XMLHttpRequest();
// post xhr to php, check for DONE and 200, and get the response
console.log(xhr.responseText);
对于 127,我得到的响应是一个字符串,正如预期的那样,其中一个字符代表 127.但是对于 128 及以上,它给了我 3 个字符,-17、-65 -67.梳理并拖网,但一无所获.很惊讶没有在网上找到任何关于从服务器到客户端传输字节的信息.我是桌面 C++ 程序员,顺便说一句,这让我难住了!
For 127, I get the response as a string with one character representing 127 as expected. But for 128 and above it gives me 3 chars, -17, -65 -67. Combed and trawled the net, but nothing. Am quite surprised to not find any info online on transmitting bytes from a server to a client. Am a desktop C++ programmer, btw hence this has me stumped!
推荐答案
因为您正在发送字节,所以您需要停止考虑文本和字符.JavaScript 在内部是 UTF-16,您将通过 HTTP 从 PHP 传输文本,PHP 可以设置自己的编码.
Because you are sending bytes, you need to stop thinking about text and characters. JavaScript is UTF-16 internally, and you'll be transporting text across HTTP from PHP which gets to set it's own encoding.
如果你想解析原始字节 在 JavaScript 中,您需要查看 数组缓冲区.收到数据后,您可以编写一个 DataView 在它上面并抓取字节.如果您只是 8 位,则也不用担心字节顺序.
If you want to parse raw bytes in JavaScript, you'll want to look into the ArrayBuffer. Once you receive your data, you can compose a DataView over it and grab the bytes. If you are 8-bit only, you shouldn't need to worry about endianness, either.
const xhr = new XMLHttpRequest();
xhr
.addEventListener(
'load',
() => {
const buffer = xhr.response;
const view = new DataView( buffer );
const byte = view.getUint8( 0 );
console.dir( byte );
}
);
xhr.open( 'GET', '/my/end-point' );
xhr.responseType = 'arraybuffer';
xhr.send();
这篇关于来自 php 的 echo char(128) 及以上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!