dongshi949737 2011-05-29 22:35
浏览 26
已采纳

js文件中的PHP变量[重复]

Possible Duplicate:
Best way to transfer an array between PHP and Javascript

How do I put the value of a PHP variable inside a Javascript variable? This is what I have now in a js file:

test=<?php echo $country; ?>;
  • 写回答

7条回答 默认 最新

  • dongxu8533486 2011-05-29 22:43
    关注

    Don't forget to properly escape your variables before passing them to JavaScript. Use json_encode() for this, as it escapes and encodes your values in a way suitable for using with JavaScript:

    test=<?php echo json_encode($country) ?>;
    

    Never simply send the variable un-encoded, as it might break things, or, worse, if the value comes from untrusted sources, compromise your security.

    Also, rename your file to .php instead of .js if you want to be able to insert dynamic PHP code inside it.

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

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料