[英]How to solve Uncaught SyntaxError: Unexpected token < in JSON at position 0 console error?
我很困扰。 我的论坛昨天和今天运行良好,然后现在我收到此错误,我的论坛不再显示或工作。 我还有另一个 js 和 php 用于发布新评论。 该评论仍在添加到我的数据库中,只是没有出现。 有谁知道这是为什么? 这是我得到的完整错误:
VM232:1 Uncaught SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at Object.success (comments.js:13)
at u (jquery.min.js:2)
at Object.fireWith [as resolveWith] (jquery.min.js:2)
at k (jquery.min.js:2)
at XMLHttpRequest.<anonymous> (jquery.min.js:2)
HTML
<div id="content" class="content">
<form id="forumPost" method='POST'>
<textarea rows="3" col="60" name="comment" placeholder="Create a Post..." id="comment"></textarea>
<button><input type='submit' name='submit' value='Post' class="post"></button>
</form>
<p id="error" class="errormessage"></p>
<p id="allcomments" class="postmessage"></p>
<div class="comment-container">
<div class="username"><!--obj.username--></div>
<div class="comment"><!--obj.comment--></div>
<div class="date"><!--obj.commDate--></div>
<div class="like"><!--obj.sentiment--></div>
</div>
</div>
JS
$(document).ready(function() {
var comments = document.getElementById("allcomments").value;
//Get Storage
var username = window.localStorage.getItem("username");
// Call Ajax for existing comments
$.ajax({
type: 'GET',
url: 'comments.php',
success: function(result) {
var arr = JSON.parse(result);
for(var i = 0; i < arr.length; i++) {
var obj = arr[i];
var output = document.getElementById("allcomments");
output.innerHTML += '<div class="comment-container"><div class="username">'+obj.username+'</div><div class="comment">'+obj.comment+'</div><div class="date">'+obj.commDate+'</div><div class="like">'+obj.sentiment+'</div></div>';
}
}
});
return false;
});
PHP
<?php
require_once('checklog.php');
require_once("db_connect.php");
require_once("functions.php");
session_start();
$username = $_POST['username'];
// Print out existing comment
$query = "SELECT comments.commDate, comments.ID, comments.username, comments.comment, users.username, comments.sentiment FROM comments LEFT JOIN users ON comments.username = users.username";
$result = mysqli_query($db_server, $query);
if (!$result)
die("Database access failed: " . mysqli_error($db_server));
while ($row = mysqli_fetch_array($result)) {
$comments[] = $row;
//CHECK THAT THE COMMENT USERID MATCHES SESSION USER ID
if ($row['username'] == $username['username']){
$comments .=" <a href='delete_post.php?pID=".$row['ID']."'>Delete</a>";
}
if(!isset($username["liked_" . $row['ID']])){
$comments .= "<a href='like.php?likeid=" . $row['ID'] ."'>Like</a>";
}else{
$comments .="Liked";
}
}
mysqli_free_result($result);
require_once("db_close.php");
echo json_encode($comments);
?>
看看这一行:
$comments[] = $row;
您将$comments
声明为数组,然后:
$comments.=" <a href='delete_post.php?pID=".$row['ID']."'>Delete</a>";
您将字符串附加到数组变量,这是绝对错误的
您从服务器返回的结果是数组和字符串的组合,结果格式无效,因此它不会转换为 js object。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.