jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON

后端 未结 7 1046
挽巷
挽巷 2020-11-22 14:04

I’m making requests to my server using jQuery.post() and my server is returning JSON objects (like { \"var\": \"value\", ... }). However, if any of

7条回答
  •  眼角桃花
    2020-11-22 14:27

    Striking a similar issue using CakePHP to output a JavaScript script-block using PHP's native json_encode. $contractorCompanies contains values that have single quotation marks and as explained above and expected json_encode($contractorCompanies) doesn't escape them because its valid JSON.

    Html->scriptBlock("var contractorCompanies = jQuery.parseJSON( '".(json_encode($contractorCompanies)."' );"); ?>
    

    By adding addslashes() around the JSON encoded string you then escape the quotation marks allowing Cake / PHP to echo the correct javascript to the browser. JS errors disappear.

    Html->scriptBlock("var contractorCompanies = jQuery.parseJSON( '".addslashes(json_encode($contractorCompanies))."' );"); ?>
    

提交回复
热议问题