【问题标题】:Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) at XMLHttpRequest.<anonymous> ((index):32)未捕获的 SyntaxError:JSON.parse (<anonymous>) 处的 JSON 输入意外结束 XMLHttpRequest.<anonymous> ((index):32)
【发布时间】:2024-05-29 18:55:01
【问题描述】:

您好,我目前正在学习如何为一个类使用 Javascript、JSON 和 PHP,我在这里遇到了我的代码问题。它告诉我有一个 Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse () at XMLHttpRequest。 ((index):32) 我正在尝试合并这个 php 函数来制作一个宁静的 api。

let xhr = new XMLHttpRequest();
        xhr.open("GET", 'api/', true);

        xhr.addEventListener("load", function () {
            let posts = JSON.parse(xhr.responseText);
            let ul = document.createElement('ul');
            document.querySelector('#app').appendChild(ul);

            for (let i = 0; i < posts.length; i++) {
                let post = posts[i];

                //lists the id
                let idLi = document.createElement('p');
                idLi.textContent = post.id;
                ul.appendChild(idLi)

                //lists the user
                let nameLi = document.createElement('p');
                nameLi.textContent = post.name;
                ul.appendChild(nameLi)



                //lists the posts
                let postsLi = document.createElement('li');
                postsLi.textContent = post.text;
                ul.appendChild(postsLi);

                //lists the likes
                let likesLi = document.createElement('p');
                likesLi.textContent = post.likes;
                ul.appendChild(likesLi)

                //lists the post dates
                let post_dateLi = document.createElement('p');
                post_dateLi.textContent = post.post_date;
                ul.appendChild(post_dateLi);

                var likeBtn = document.createElement('BUTTON');
                likeBtn.id = 'likeBtn'; //set the id of the btn to call
                var likeBtnText = document.createTextNode("Like");
                likeBtn.appendChild(likeBtnText);
                ul.appendChild(likeBtn);

                likeBtn.addEventListener('click', function () {



                }, true);
                var dislikeBtn = document.createElement('BUTTON');
                dislikeBtn.id = 'dislikeBtn'; //set the id of the btn to call
                var dislikeBtnText = document.createTextNode("Dislike");
                dislikeBtn.appendChild(dislikeBtnText);
                ul.appendChild(dislikeBtn);

                likeBtn.addEventListener('click', function () {



                }, true);
                var replyBtn = document.createElement('BUTTON');
                replyBtn.id = 'ReplyBtn'; //set the id of the btn to call
                var replyBtnText = document.createTextNode("Reply");
                replyBtn.appendChild(replyBtnText);
                ul.appendChild(replyBtn);

                replyBtn.addEventListener('click', function () {



                }, true);
            }

        });

        xhr.send();
    </script>
</body>

</html>

    class Handler {
    private $regex;
    private $func;
    private $method = null;
    public function __construct($regex, $method, $func) {
        $this->regex = $regex;
        $this->func = $func;
        $this->method = $method;
    }
    public function handle($url, $method) {
        $params = null;
        $f = $this->func;
        // todo: also check whether the method matches
        if($method !== $this->method)
        {
            return FALSE;
        }
        // preg_match does a regular expression match in PHP
        if(preg_match($this->regex, $url, $params)) {
            $f($params);
            return TRUE;
        }
        return FALSE;
    }
}
class Router {
    private $handlers = array();
    function register($regex, $method, $function) {
        $this->handlers[] = new Handler($regex, $method, $function);
    }
    // TODO: Add get, post, put and delete register
    function get($regex, $function)
    {
        $this->register($regex, 'GET', $function);

    }
    function post($regex, $function)
    {
        $this->register($regex, 'POST', $function);
    }
    function put($regex, $function)
    {
        $this->register($regex, 'PUT', $function);
    }
    function delete($regex, $function)
    {
        $this->register($regex, 'DELETE', $function);
    }
    function route($url, $method) {
        $params = null;
        foreach ($this->handlers as $handler) {
            if($handler->handle($url, $method)) {
                return;
            }
        }
    }
}
$router = new Router();

这是使用路由器和处理程序中的方法的代码

$router->get('#^/api/(\d+)#', function($params) {
$conn = new PDO ($DB_DSN,$DB_USER, $DB_PASSWORD);
$id = $params[1];
$query = "SELECT * FROM CinemaPost WHERE id=?";
$stmt = $conn->prepare($query);
$stmt->bindValue(1,$id, PDO::PARM_INT);
$stmt->execute();
$result = $stmt;
if($r = $result->fetch())
{
$response = [
    "id" => $row['id'],
    "name" => $row['name'],
    "text" => $row['text'],
    "post_date" => $row['post_date'],
    "likes" => $row['likes'],
    "url" => build_post_uri($row['reply_to']),
    "replies" => [] 
]; 

}
echo json_encode($response);
});

【问题讨论】:

  • 您可以使用浏览器的开发工具来检查实际响应。但我可以告诉你没有$row 变量,你使用$r 来保存查询的第一个结果
  • 你正处于编程变得有趣的地步,它被称为调试。使用 ^^ 提到的 devtools,添加额外的代码来检查变量的值。自己解决这个问题会增加你的编程知识。

标签: javascript php sql


【解决方案1】:

在您的代码中,尝试更改

let posts = JSON.parse(xhr.responseText);

let posts = JSON.parse(xhr.response);

这应该会有所帮助。我遇到了类似的问题,在 rigmarole 之后,我通过简单地将 responseText 更改为 response 来解决它。

我认为您的数据源是一个对象数组。

【讨论】: