dth20986 2014-04-04 14:18
浏览 70

使用php中创建的变量从PHP调用Javascript函数

I have a javascript function in a file comment_insert.js:

  function comment_insert(data,ul_id) {

        var t = '';
        t += '<li class="comment-holder" id="_' + data.comment_id + '">';
        t += '<div class="user-img">';
        t += '<img src="' + data.profile_img + '" class="user-img-pic" />';
        t += '</div>';
        t += '<div class="comment-body">';
        t += '<h3 class="username-field" >' + data.Username + '</h3>';
        t += '<div class="comment-text">' + data.comment + '</div>';
        t += '</div>';
        t += '<div class="comment-buttons-holder">';
        t += '<ul>';
        t += '<li class="delete-btn">[x]</li>';
        t += '</ul>';
        t += '</div>';
        t += '</li>';

        $('#' + ul_id).prepend(t);
    }

I want to call this function from a php file display.php as:

$smthng = new stdClass();
        $smthng->comment_id = 24;
        $smthng->Userid = 1;
        $smthng->comment = "Hard coded comments";
        $smthng->Username = "Sagar_username"; 
        //$smthng->profile_img = "images/Setting-icon.png";


        $data =  json_encode($smthng);
                $ul_id = "ul218";

 comment_insert(jQuery.parseJSON($data),$ul_id);

The function being called is the same as in comment_insert.js which accepts 2 inputs (data and ul_id). These are being created in display.php and then I want to execute the function.

  • 写回答

2条回答 默认 最新

  • doupa9062 2014-04-04 14:23
    关注

    Assuming that the PHP code is in the same file as Javascript and is being used for front end out put to the browser, you can do this:

    <?php
    $smthng = new stdClass();
            $smthng->comment_id = 24;
            $smthng->Userid = 1;
            $smthng->comment = "Hard coded comments";
            $smthng->Username = "Sagar_username"; 
            //$smthng->profile_img = "images/Setting-icon.png";
    
    
            $data =  json_encode($smthng);
                    $ul_id = "ul218";
    ?>
    <script type="text/javascript">
        comment_insert(jQuery.parseJSON(<?php echo $data ?>), <?php echo $ul_id ?>);
    </script>
    

    However, if this is not in a file that is producing output to the browser, you cannot execute Javascript server-side

    评论

报告相同问题?

悬赏问题

  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失