php json_encode & jquery parseJSON single quote issue

后端 未结 5 2049
庸人自扰
庸人自扰 2020-12-24 01:40

I searched and read most of the related topics, but they weren\'t what I was looking for.

I\'ve a JSON enocded string with json_encode PHP function:

5条回答
  •  無奈伤痛
    2020-12-24 01:47

    For the broader problem of passing a JSON-encoded string in PHP (e.g., through cURL), using the JSON_HEX_APOS option is the cleanest way to solve this problem. This would solve your problem as well, although the previous answers are correct that you don't need to call parseJSON, and the JavaScript object is the same without calling parseJSON on $data.

    For your code, you would just make this change:

    json_encode($var) to json_encode($var, JSON_HEX_APOS).

    Here's an example of the correctly encoded data being parsed by jQuery: http://jsfiddle.net/SuttX/

    For further reading, here's an example from the PHP.net json_encode manual entry Example #2:

    $a = array('',"'bar'",'"baz"','&blong&', "\xc3\xa9");
    
    echo "Apos: ",    json_encode($a, JSON_HEX_APOS), "\n";
    

    This will output:

    Apos: ["","\u0027bar\u0027","\"baz\"","&blong&","\u00e9"]
    

    A full list of JSON constants can be found here: PHP.net JSON constants

提交回复
热议问题