javascriptajaxxmlhttprequest

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())?


Solution

  • 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 functions 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" }