doulangpeng3933 2019-07-16 19:55
浏览 92

将php数组转换为javascript utf-8数组

I have a products table that has foreign characters. Now I am trying to use the php array in javascript to narrow a dropdown box as the user types. Everything works except when there is a foreign character (like a carrot or tilde above a letter). How can I encode the the php array into the javascript array with these characters?

$jpro=json_encode($pro, JSON_HEX_APOS|JSON_HEX_QUOT|JSON_UNESCAPED_UNICODE);
var phpPro=<?php echo $jpro; ?>;

The errors Im getting are

var phpPro=;
"Uncaught SyntaxError: Unexpected token ;"
  • 写回答

1条回答 默认 最新

  • duanguzhong5776 2019-07-16 21:07
    关注

    With JSON_HEX_APOS|JSON_HEX_QUOT you're telling json_encode to convert apostrophes and quotes to \u0027 and \u0022 respectively, but then negate it with JSON_UNESCAPED_UNICODE. And the reason you're getting that error is because you haven't put the PHP code in the variable inside quotes.

    Now, since json_encode returns an array with quotes, e.g. [ "Österreich", "Gemüse" ], you can't just place the code inside them, but need to use apostrophes.

    Ultimately, the following would be correct*:

    $jpro = json_encode($pro, JSON_UNESCAPED_UNICODE);
    var phpPro = '<?php echo $jpro; ?>';
    

    Granted, this is going to return a string, not an array if that was your intention. If you want to transform it back to an array, just use JSON.parse:

    var phpPro = JSON.parse('<?php echo $jpro; ?>');
    

    * correct in the sense that it does what you're asking, but you really should never mix JavaScript and PHP together — especially not if you're dealing with user input.

    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?