简体   繁体   中英

Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) at XMLHttpRequest.<anonymous> ((index):32)

Hi I'm currently learning how to user Javascript, JSON and PHP for a class an I'm having an issue with my code here. it's telling me that there is an Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse () at XMLHttpRequest. ((index):32) I'm trying to incorporate this php function to make a restful 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();

And this is the code that is using the methods from the router and handler

$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);
});

in your code, try changing

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

to

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

That should help. I had a similar problem and after rigmarole, I fixed it by simply changing responseText to response.

I presume your data source is an array of objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM