简体   繁体   English

PHP + JS + AJAX:JSON中的意外令牌{

[英]PHP + JS + AJAX: Unexpected token { in JSON

On trying to return some data from a GET request via AJAX , I'm continuously greeted with this nasty error message ...Unexpected token { in JSON... and I can clearly see where it's coming from. 在尝试通过AJAXGET请求返回一些数据时,我不断收到这个令人讨厌的错误消息...Unexpected token { in JSON...我可以清楚地看到它的来源。 Note that this only happens if I have more than one(1) item being returned from the database. 请注意,仅当我从数据库返回了多个(1)项时,才会发生这种情况。 If I only have one(1) item I am able to access it data.id , data.user_name , so on and so forth. 如果我只有一个(1)项,则可以访问它data.iddata.user_name ,依此类推。

{  
   "id":"39",
   "user_id":"19",
   "user_name":"Brandon",
   "content":"Second Post",
   "date_created":"2018-01-24 21:41:15"
}/* NEEDS TO BE A ',' RIGHT HERE */ {  
   "id":"37",
   "user_id":"19",
   "user_name":"Brandon",
   "content":"First",
   "date_created":"2018-01-24 15:19:28"
}

But I can't figure out how to fix it. 但是我不知道如何解决它。 Working with data, arrays, and objects is an artform I have yet to master. 我尚未掌握处理数据,数组和对象的一种艺术形式。

JAVASCRIPT (AJAX) JAVASCRIPT(AJAX)

const xhr = new XMLHttpRequest();

xhr.open('GET', 'http://localhost/mouthblog/test.php');
xhr.onload = () => {
  if (xhr.status == 200) {
    const data = xhr.responseText;
    const jsonPrs = JSON.parse(data);
    console.log(jsonPrs);
  } else {
    console.log('ERROR');
  }
};
xhr.send();

PHP (this is where the data is coming from) PHP(这是数据的来源)

<?php

class BlogRoll extends Connection {
  public function __construct() {
    $this->connect();

    $sql    = "SELECT `id`, `user_id`, `user_name`, `content`, `date_created`
               FROM `posts`
               ORDER BY `date_created` DESC";
    $query  = $this->connect()->prepare($sql);
    $result = $query->execute();

    if ($result) {
      while ($row = $query->fetch(PDO::FETCH_OBJ)) {
        header('Content-Type: application/json;charset=UTF-8');
        echo json_encode($row);
      }
    } else {
      echo 'NO POSTS TO DISPLAY';
    }
  }
}

I've been at this for a couple of hours now, everything similar to my problem on SO seems to be something different and I can't really find a decent plain JavaScript tutorial on returning real data. 我已经花了几个小时了,所有与我在SO上的问题类似的东西似乎有所不同,我真的找不到真正的关于返回真实数据的普通JavaScript教程。 Everyone wants to use jQuery. 每个人都想使用jQuery。

The reason why your code is failing is because you are using 代码失败的原因是因为您正在使用

echo json_encode($row);

This will echo an array for every row, but it is not valid JSON. 这将为每行回显一个数组,但它不是有效的JSON。 I have corrected your PHP code (note: it has not been tested) 我已经更正了您的PHP代码(注意:它尚未经过测试)

<?php

class BlogRoll extends Connection {
  public function __construct() {
    $this->connect();

    $sql    = "SELECT `id`, `user_id`, `user_name`, `content`, `date_created`
               FROM `posts`
               ORDER BY `date_created` DESC";
    $query  = $this->connect()->prepare($sql);
    $result = $query->execute();

    $returnArray = array(); // Create a blank array to put our rows into

    if ($result) {
      while ($row = $query->fetch(PDO::FETCH_OBJ)) {
        array_push($returnArray, $row); // For every row, put that into our array
      }
    } else {
        // Send the JSON back that we didn't find any data using 'message'
        $returnArray = array(
            "message" => "No data was found"
        );
    }

    header('Content-Type: application/json;charset=UTF-8'); // Setting headers is good :)
    exit(json_encode($returnArray)); // Exit with our JSON. This makes sure nothing else is sent and messes up our response.

  }
}

Also, you stated this: 此外,您还说过:

If I only have one(1) item I am able to access it data.id, data.user_name, so on and so forth.

That is correct because the array only contains that one item. 这是正确的,因为数组仅包含该一项。 The example you would access it via data.0.id, data.1.id, data.2.id, etc as each row is in its own array. 该示例将通过data.0.id,data.1.id,data.2.id等访问它,因为每一行都在其自己的数组中。

You must print only once, eg a data "package" from which you will reference the items on the client-side correspondingly. 您只能打印一次,例如,数据“包装”,您将从中相应地引用客户端上的项目。 But in your code you're actually printing for each row a data "package". 但是在您的代码中,实际上是为每一行打印一个数据“包”。

The solution is to create an array and save the whole fetched data into it. 解决方案是创建一个数组并将所有获取的数据保存到其中。 After that the array should be json-encoded and printed. 之后,应该对数组进行json编码和打印。

if ($result) {
    // Save the fetched data into an array (all at once).
    $fetchedData = $query->fetchAll(PDO::FETCH_ASSOC);

    // Json-encode the whole array - once.
    // header('Content-Type: application/json;charset=UTF-8');
    echo json_encode($fetchedData);
} else {
    echo 'NO POSTS TO DISPLAY';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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