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

    评论

报告相同问题?