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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog