我从服务器的响应中收到此(JSON.parse:JSON数据第1行第1列的数据意外结束)错误。我为JSON.stringify(user)做了console.log,它按原样显示了对象,即使数据已经存储到数据库了。
这是我的服务

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();
?>

最佳答案

继承人更新的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);
 }

 ?>

07-24 09:51
查看更多