【发布时间】:2021-04-09 22:23:15
【问题描述】:
我有一个脚本 (Users.php),它使用 JSON_encode 在 HTML 表中显示对象数组。
如:
Users.php:
html //空表
脚本//使用json编码填充表格,获取php数组并显示表格中的内容
myPhp.php:
从数据库中获取信息并创建数组。
我的 php 文件运行良好,我的脚本也是如此。唯一的问题是当我使用 JSON_encode 将数组从 php 获取到脚本时,它显示错误 : Uncaught SyntaxError: Unexpected token '
我的用户.php:
<body >
<!-- adding user -->
<form class ="formArea" id = "addUser" action = "addUsers.php" method="POST">
<!-- addUsers.php will add users to the database then display Users.php again -->
</form>
<!-- display users -->
<table id="usersTable">
<!-- table to display user info -->
</table>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <!--jquery-->
<script>
//display all users in table
var users = <?php echo JSON_encode($rows); ?>
displayUsers(users);
function displayUsers(users){
for(i = 0; i<users.length; i++)
{
//create table row
//add user information to the row
}
}
</script>
</body>
我的 myPhp.php:
<?php
// fur UI Users.php
// calls all users from the db and displays them in users table
$sql = new mysqli("localhost","root","","atds");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
exit();
}
$query = "SELECT * FROM users";
$result = $sql->query($query);
while($row = $result->fetch_object())
{
$rows[]=$row;
}
// Close connection
$result->close();
$sql->close();
?>
我尝试过的:
我尝试在使用 json_encode 之前包含 php 文件
<?php include'myPhp.php' ?>
var users = <?php echo json_encode($rows); ?>
这在我运行 Users.php 时有效,但如果我添加用户(通过在此网页中提交表单),添加用户文件在添加用户后再次读取 Users.php,用户最终不会显示,我会有同样的错误: 未捕获的语法错误:意外的标记“
有没有其他方法可以使用不会导致此错误的 JSON_encode?p>
【问题讨论】:
-
忽略上面的评论,我认为你需要使用
JSON.parse(users)解析你的json数据,因为json_encode返回一个字符串而不是实际的json对象。 -
我尝试在 users= JSON_encode() 之后添加 JSON_ parse(users)。我仍然遇到同样的错误。我不明白如果 encode 返回一个字符串,那么当我包含 myPhp.php 时,我的 Users.php 是如何工作的
标签: javascript php json backend jsonencoder