duanli9591 2014-02-27 09:57
浏览 34
已采纳

来自PHP的JavaScript转义字符

I'm having the simple script as follows,

<?php

$actionbutton = '<input type="button" onclick="document.location.href=\'/backoffice_dev.php/currency/edit/EUR\';" value="Edit">';
$tr = '<tr><td>'.$addNewCurrencyPOST["id"].'</td>
<td><div class="led on"></div></td>
<td>'.$addNewCurrencyPOST["symbol"].'</td>
<td>'.$addNewCurrencyPOST["symbolhtml"].'</td>
<td>'.$addNewCurrencyPOST["usdrate"].'</td>
<td>'.$addNewCurrencyPOST["eurrate"].'</td>
<td>'.$actionbutton.'</td></tr>';

?>

<script>
    var tr = "<?php echo $tr ?>";
    console.log(tr);
</script>

But it is throwing a error "Uncaught SyntaxError: Unexpected token ILLEGAL " in chrome. Note that there is no special characters in any of the values coming from PHP. I'm using prototype JS in this page. Is it causing this problem? Because i don't have any knowledge on that.

And how to append this to a table without using insertRow and insertCell functions? Please help guys..

  • 写回答

4条回答 默认 最新

  • doutinghou6980 2014-02-27 10:01
    关注

    Note that there is no special characters in any of the values coming from PHP.

    You have literal new lines (which are not allowed in JS string literals). As dhidy points out, you also have unescaped " characters in the data and are delimiting the JS string with " characters.

    Use json_encode to turn a PHP string into a (suitably escaped) JavaScript string literal. Note that will generate the quote characters around the data so you shouldn't add them separately.

    var tr = <?php echo json_encode($tr); ?>;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器