将PHP变量分配给Javascript变量不起作用

时间:2015-06-23 14:44:17

标签: javascript php

我目前遇到这个问题。我想在Javascript中使我的一个变量具有PHP值。这就是我的意思:

<script>
    JSvariable = <?php echo $PHPvariable; ?>;
</script>

由于某些原因无效。这是我的完整(代码片段)代码:

<script>
    currentreplyid = <?php echo $allpostcomments[$key]['replyid']; ?>;
    $('#parentcommentholder').val(currentreplyid);
</script>

我确信这是一个愚蠢的错误,但我似乎无法找到它!问题是什么?谢谢!

PS #parentcommentholder是一个输入字段,在该字段应该被更改之后它只有值0。

以下是一些消息来源:

<?php
$postcommentsquery = "SELECT * FROM comments WHERE parent = :parent AND postid = :postid ORDER BY datecreated DESC";
$postcommentsparams = array(':parent' => $allreplies[$key]["postid"],
                            ':postid' => $postid);
try{
    $postcommentsstmt = $connection->prepare($postcommentsquery);
    $postcommentsresult = $postcommentsstmt->execute($postcommentsparams);
}
catch(PDOException $ex){
    echo ("Failed to run query: " . $ex->getMessage());
}
$allpostcomments = $postcommentsstmt->fetchAll();
foreach ($allpostcomments as $key => $value) {
?>
    <script>
    var currentreplyid = <?php echo $allpostcomments[$key]['replyid']; ?>;
    $('#parentcommentholder').val(currentreplyid);
    </script>

    <input id="parentcommentholder"></div>

2 个答案:

答案 0 :(得分:3)

不要忘记提供引号'"。使用以下:

<script>
    var JSvariable = '<?php echo $PHPvariable; ?>';
    //or
    var JSvariable = "<?php echo $PHPvariable; ?>";
</script>

原因:如果php变量包含字符串,并且如果将其分配给javascript变量,我们将不会给出如下引用:

<?php $PHPvariable = 'String';?>
var JSvariable = <?php echo $PHPvariable; ?>;

将转变为:

var JSvariable = String;//which will give error in javascript

但是,如果PHP变量包含如下数值:

,这将正常工作
<?php $PHPvariable = 2;?>
var JSvariable = <?php echo $PHPvariable; ?>;

将转变为:

var JSvariable = 2;//which will work perfect

完整的代码应该是:

<script>
    var currentreplyid = "<?php echo $allpostcomments[$key]['replyid']; ?>";
    //or if you are sure your variable contains int value
    var currentreplyid = parseInt("<?php echo $allpostcomments[$key]['replyid']; ?>");
    $('#parentcommentholder').val(currentreplyid);
</script>

答案 1 :(得分:0)

尝试下面而不是使用javascript(因为我认为你不需要它):

<?php
$postcommentsquery = "SELECT * FROM comments WHERE parent = :parent AND postid = :postid ORDER BY datecreated DESC";
$postcommentsparams = array(':parent' => $allreplies[$key]["postid"],
                            ':postid' => $postid);
try{
    $postcommentsstmt = $connection->prepare($postcommentsquery);
    $postcommentsresult = $postcommentsstmt->execute($postcommentsparams);
}
catch(PDOException $ex){
    echo ("Failed to run query: " . $ex->getMessage());
}
$allpostcomments = $postcommentsstmt->fetchAll();
foreach ($allpostcomments as $key => $value) {
?>
<input id="parentcommentholder" value="<?php echo ((int)$allpostcomments[$key]['replyid']>0) ? $allpostcomments[$key]['replyid'] : 0; ?>" />
<?php
}
?>

如果您肯定确定$ allpostcomments [$ key] ['replyid']带回一个值,这应该没有任何问题。