Javascript:Uncaught SyntaxError:意外的令牌<

时间:2017-02-22 06:55:17

标签: javascript php json

我有这些代码,它将php变量存储到全局javascript变量中。所有模块都在同一个文件中,但仍然在 rowNum1的行中得到 Uncaught SyntaxError:Unexpected token< : -

<script type="text/javascript">
    var glo = 0;
    var rowNum = <?php echo $_GET['SN'];?>;
    var newnames = new Array();
    var rowNum1 = "";
    var tempVal = "";
    var destTextarea = "";
    newnames=<?php echo json_encode($userinfoarr); ?>; //This varaible initialisation works fine


    function fetchNext(){
            if (glo++ === 0)
            {
                if(rowNum < newnames.length)
                {   
                    document.getElementById("Txt0").value = rowNum;
                    document.getElementById("Txt1").value = newnames[rowNum];
                    tempVal = newnames[rowNum];
                }
                rowNum++;
            }
            else
            {
                rowNum1=<?php echo json_encode($sln); ?>; //This one throws an Uncaught Syntax error
                if(rowNum1 < newnames.length)
                {   
                    document.getElementById("Txt0").value = rowNum1;
                    document.getElementById("Txt1").value = newnames[rowNum1];
                    tempVal = newnames[rowNum1];
                }
                rowNum1++;  
                console.log("test");
            }
    }
    </script>

这是 $ sln

的php代码
<?php
    if($_SERVER['REQUEST_METHOD'] == 'POST')
    {
        if(isset($_POST['Txt0']))
        {
            $sln = $_POST['Txt0'];
        }
    }
?>

这是 $ userinfoarr

的php代码
<?php
    require_once('config.php');
    $result = mysqli_query($conn, "SELECT tweet from tweet");
    $userinfoarr = array();
    while ($row_user = mysqli_fetch_array($result,MYSQLI_ASSOC))
    {
        $userinfo = $row_user["tweet"];
        $push=array_push($userinfoarr, $userinfo);
    }
?>

任何人都可以帮我解决这个问题,因为我无法理解这种情况? 这是浏览器内部错误的屏幕截图 enter image description here enter image description here

3 个答案:

答案 0 :(得分:0)

更改您的PHP代码,如下所示。分配$sln默认值

<?php
    $sln = ""; //<---- assign default value to $sln
    if($_SERVER['REQUEST_METHOD'] == 'POST')
    {
        if(isset($_POST['Txt0']))
        {
            $sln = $_POST['Txt0'];
        }
    }
?>

答案 1 :(得分:0)

做这样的事情

将$ sln代码修改为

<?php
    if($_SERVER['REQUEST_METHOD'] == 'POST')
    {
        if(isset($_POST['Txt0']))
        {
            $sln = $_POST['Txt0'];

    echo "<script type='text/javascript'>var sln='$sln'</script>";

        }
    }
?>

和脚本

 {
       rowNum1 = sln; // 

                if(rowNum1 < newnames.length)
                {   
                    document.getElementById("Txt0").value = rowNum1;
                    document.getElementById("Txt1").value = newnames[rowNum1];
                    tempVal = newnames[rowNum1];
                }
                rowNum1++;  
                console.log("test");
     }

答案 2 :(得分:-1)

对PHP代码使用单引号:

var rowNum = '<?php echo $_GET['SN'];?>';