【问题标题】:JSON.parse: unexpected end of data at line 1 column 1 of the JSON data( Angular2 backend php server SQL)JSON.parse:JSON数据的第1行第1列的数据意外结束(Angular2后端php服务器SQL)
【发布时间】:2018-04-07 05:29:39
【问题描述】:

我在来自服务器的响应中收到此错误(JSON.parse:JSON 数据的第 1 行第 1 列的数据意外结束)错误。我为 JSON.stringify(user) 做了 console.log,它按原样显示了对象。甚至数据也被存储到数据库中。 这是我的服务。ts

signup(user: User) {

    const body = JSON.stringify(user);

    const headers = new Headers({'Content-Type': 'application/json'});
    const requestOptions = new RequestOptions({method : RequestMethod.Post,headers : headers});
    return this.http.post('url', body,requestOptions)
        .map((response: Response) => response.json())


}

signin(user: User) {
    const body = JSON.stringify(user);
    const headers = new Headers({'Content-Type': 'application/json'});
    return this.http.post('url', body, {headers: headers})
        .map((response: Response) => response.json())

}

logout() {
    localStorage.clear();
}

isLoggedIn() {
    return localStorage.getItem('token') !== null;
}

这是我的 php 文件

<?php
include "db.php";
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$data = json_decode(file_get_contents("php://input"));
//print_r($data);
/*$firstname = mysql_real_escape_string($data->firstName);
$lastname = mysql_real_escape_string($data->lastName);
$email = mysql_real_escape_string($data->email);
$password = mysql_real_escape_string($data->password);*/

$sql = "INSERT INTO `tbl_user`(`firstname`, `lastname`, `email`,  `password`) VALUES                       ('$data->firstName','$data->lastName','$data->email','$data->password')";
if($data->firstName){
$qry = $conn->query($sql);
}

$conn->close();
?>

【问题讨论】:

  • 如果错误在服务器响应中,显示服务器响应是什么。在这里它似乎没有返回任何东西
  • 感谢回复@David。我找到了解决方案。它在我的 php 文件中。我没有对响应进行 JSON 编码。

标签: php mysql json angular


【解决方案1】:

这是更新的 php 文件

<?php
include "db.php";
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$data = json_decode(file_get_contents("php://input"));

$firstname = $mysqli->real_escape_string($data->firstName);
$lastname = $mysqli->real_escape_string($data->lastName);
$email = $mysqli->real_escape_string($data->email);
$password = $mysqli->real_escape_string($data->password);
$sql = "INSERT INTO `tbl_user`(`firstname`, `lastname`, `email`, `password`) VALUES ('$data->firstName','$data->lastName','$data->email','$data->password')";
if (mysqli_query($mysqli,$sql))
 {
 $arr = array('sucess' => "Records save");
 $jsn = json_encode($arr);
 print_r($jsn);
 }
 else 
 {
 $arr = array('failed' => "No records save", 'error' => '');
 $jsn = json_encode($arr);
 print_r($jsn);
 }

 ?>

【讨论】:

    猜你喜欢
    • 2020-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-30
    • 2020-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多