简体   繁体   中英

How decode HEX in XMLHtppRequest?

I have a site and I used AJAX. And I got some problems.

Server return JSON string something like this {a:"x48\\x65\\x6C\\x6C\\x6F"} .

Then in xx.responseText , we have this string '{a:"\\x48\\x65\\x6C\\x6C\\x6F"}' .

But if I create JavaScript string "\\x48\\x65\\x6C\\x6C\\x6F" then I have "Hello" and not HEX!

Is it possible get in xx.responseText "real" text from HEX (automatically, without .replace() )?

If the output is at all regular (predictable), .replace() is probably the simplest.

var escapeSequences = xx.responseText.replace(/^\{a:/, '').replace(/\}$/, '');

console.log(escapeSequences === "\"\\x48\\x65\\x6C\\x6C\\x6F\""); // true

Or, if a string literal that's equivalent in value but may not otherwise be the same is sufficient, you could parse (see below) and then stringify() an individual property.

console.log(JSON.stringify(data.a) === "\"Hello\""); // true

Otherwise, you'll likely need to run responseText through a lexer to tokenize it and retrieve the literal from that. JavaScript doesn't include an option for this separate from parsing/evaluating, so you'll need to find a library for this.

" Lexer written in JavaScript? " may be a good place to start for that.


To parse it:

Since it appears to be a string of code, you'll likely have to use eval() .

var data = eval('(' + xx.responseText + ')');

console.log(data.a); // Hello

Note: The parenthesis make sure {...} is evaluated as an Object literal rather than as a block .


Also, I'd suggest looking into alternatives to code for communicating data like this.

A common option is JSON , which takes its syntax from JavaScript, but uses a rather strict subset. It doesn't allow function s or other potentially problematic code to be included.

var data = JSON.parse(xx.responseText);

console.log(data.a); // Hello

Visiting JSON.org , you should be able to find a reference or library for the choice of server-side language to output JSON.

{ "a": "Hello" }

Why not just let the JSON parser do its job and handle the \\x escape sequences, and then just convert the string back to hex again afterwards, eg

function charToHex(c) {
    var hex = c.charCodeAt(0).toString(16);
    return (hex.length === 2) ? hex : '0' + hex;
}

"Hello".replace(/./g, charToHex);  // gives "48656c6c6f"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM