dqk77945 2014-08-26 13:22
浏览 17
已采纳

PHP / jQuery - 意外的标识符

I am setting an jQuery array with PHP, like this:

    <script type='text/javascript'>
    var postQuote = new Array();
    postQuote[<?php echo $post['post_id']; ?>] = <?php echo mysql_real_escape_string(html_entity_decode($post['post_text'])); ?>
   </script>

My problem is, that $post['post_text']; can literally contain all characters. Therefore, I am getting an unexpected identifier error with jQuery.

My question is: how can I avoid this?

  • 写回答

1条回答 默认 最新

  • douzhanglu4591 2014-08-26 13:24
    关注

    Why don't you do a json_encode. json_encode will convert your PHP variables into a variable that's usable by JavaScript. This also might remove the need to use html_entity_decode on most occasions, since this is not really something you should be doing to convert something that will be used by JavaScript. mysql_real_escape_string is not needed at all.

    <script type='text/javascript'>
        var postQuote = new Array();
        postQuote[<?php echo json_encode($post['post_id']); ?>] = <?php echo json_encode($post['post_text']); ?>
    </script>
    

    I would also set them as separate variables so that they're easier to debug and keep track of:

    <script type='text/javascript'>
        var postQuote = new Array();
        var postQuoteKey = <?php echo json_encode($post['post_id']); ?>;
        var postQuoteValue = <?php echo json_encode($post['post_text']); ?>;
        // See what the key and value are
        console.log(postQuoteKey);
        console.log(postQuoteValue);
        postQuote[postQuoteKey] = postQuoteValue;
    </script>
    

    The following example works as expected:

    <script>
    // Number
    console.log(<?php echo json_encode(1); ?>); 
    // String
    console.log(<?php echo json_encode("hello"); ?>);
    // Boolean
    console.log(<?php echo json_encode(false); ?>);
    // Boolean
    console.log(<?php echo json_encode(true); ?>);
    // Array
    console.log(<?php echo json_encode(array(1,2,3)); ?>);
    // Outputs a JavaScript object
    console.log(<?php echo json_encode(array("a" => 345, "b" => '242', "c" => 'hello')); ?>);
    </script>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启