duanpan3166 2017-10-31 01:35
浏览 75
已采纳

转义从PHP生成的javascript对象中的引号

I feel like this must surely be a duplicate of an oft-answered question, but I cannot find an answer that addresses my particular issue.

I am loading data from MySQL via PHP, including some strings and a JSON-encoded string. This data may contain special characters, entered by the user.

I then combine this data into a PHP array, then json_encode it and read it into javascript using JSON.parse.

My issue is that an apostrophe in any of these strings will interrupt the javascript, preventing the JSON.parse from completing.

I think there are three ways to solve this:

  1. Do some sort of encoding on the user-entered data before it gets saved to the database
  2. Escape the special characters when loading from the MySQL (using htmlspecialchars() or similar), though this will be difficult when loading data that's stored as a JSON string (I suppose I could decode it, then loop through and escape special characters in each element, then re-encode it).
  3. Escape the special characters in javascript, somehow. But I don't know how I'd do this.

I would have to say that special character encoding is probably the single-most frustrating aspect of web development, as it causes me so many unexpected errors and I struggle to understand the different functions and when they should be used.

EDIT:

var feedback = JSON.parse('{"721103":[{"sessionid":"45","feedback":{"praise":["","",""],"development":["","",""]}},{"sessionid":"46","feedback":{"praise":["Test","Test's",""],"development":["","",""]}}') ;

The apostrophe in Test's breaks the javascript

  • 写回答

3条回答 默认 最新

  • donglin9717 2017-11-18 15:27
    关注

    My attempts to edit @kmoser's answer with the actual solution that worked were rejected in peer review, so here's what worked. All credit to @kmoser:

    $json_feedback = preg_replace( preg_quote('/\u/'), '\\\\\\\\u', json_encode( $feedback, JSON_HEX_APOS | JSON_HEX_QUOT ) );

    It works by replacing singles and double quotes with hex strings when the data is retrieved from the MySQL database. For reasons I don't understand, that still broke the javascript, so I then did a preg_replace to put an additional backslash before the escaped code.

    Notice how many backslashes I had to put in to persuade the preg_replace to put in the additional backslash to prevent the javascript breaking. I may be able to get away with fewer backslashes, the number that appears here is mostly out of sheer frustration with this silly issue!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算