Javascript 为什么在ajax请求中会出现与内容类型相关的JSON错误?
在尝试向我的PHP API发出ajax请求(使用Angularjs)时,我遇到以下错误Javascript 为什么在ajax请求中会出现与内容类型相关的JSON错误?,javascript,php,angularjs,json,content-type,Javascript,Php,Angularjs,Json,Content Type,在尝试向我的PHP API发出ajax请求(使用Angularjs)时,我遇到以下错误 SyntaxError: Unexpected token n in JSON at position 24 我非常感谢你的帮助。谢谢 以下是我的代码: var data = {"username":"sarahexample", "password":"5f4dcc3b5aa765d61d8327deb882cf99"}; $http({ method: 'POST', url: 'htt
SyntaxError: Unexpected token n in JSON at position 24
我非常感谢你的帮助。谢谢
以下是我的代码:
var data = {"username":"sarahexample", "password":"5f4dcc3b5aa765d61d8327deb882cf99"};
$http({
method: 'POST',
url: 'http://localhost/API/auth',
data : JSON.stringify(data)
}).then(function successCallback(response) {
console.log(response);
}, function errorCallback(response) {
console.log(response);
});
下面是PHP auth函数,它在请求端点时执行
protected function auth($parameters) {
if ($this->method == 'POST') {
//echo the POST data back to the client side to test it's working
//This works when I take out the php Content-Type header
echo json_encode($_POST);
} else {
//echo "Only accepts POST requests";
}
}
在我的PHPAPI中,我有下面的标题(,当去掉它时,一切正常,但是我希望它与标题一起工作
我尝试在上面的标题中留下,并在ajax请求中添加contentType:'application/json'
,如下所示(但这并没有解决json错误):
在控制台的“网络”选项卡中:
Request URL:http://localhost/API/auth
Request Method:POST
Status Code:200 OK
Remote Address:[::1]:80
Referrer Policy:no-referrer-when-downgrade
Response Headers
view source
Access-Control-Allow-Methods:*
Access-Control-Allow-Origin:*
Connection:Keep-Alive
Content-Length:6
Content-Type:application/json
Date:Thu, 28 Sep 2017 17:17:31 GMT
Keep-Alive:timeout=5, max=100
Server:Apache/2.4.27 (Win64) PHP/5.6.31
X-Powered-By:PHP/5.6.31
Request Headers
view source
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Content-Length:73
Content-Type:application/json
Host:localhost
Origin:http://localhost
Pragma:no-cache
Referer:http://localhost/phonegap_tut/
Request Payload
view source
{username: "sarahexample", password: "5f4dcc3b5aa765d61d8327deb882cf99"}
password
:
"5f4dcc3b5aa765d61d8327deb882cf99"
username
:
"sarahexample"
正确的方法是在echo之前检查JSON输出
// Check if your JSON conversion succeed
$json = json_encode($_POST);
if ($json === false) {
// JSONify the error message:
$json = json_encode(array("jsonError", json_last_error_msg()));
if ($json === false) {
// This should not happen, but we go all the way now:
$json = '{"jsonError": "unknown"}';
}
// Set HTTP response status code to: 500 - Internal Server Error
http_response_code(500);
}
echo $json;
我发现了错误发生的原因。这是几件事的结合 首先,我犯了一个愚蠢的错误,我不小心重复了两次数据: 我有一个名为MyAPI.php的类,它包含auth方法。我在这里回显数据,而我本应该在另一个名为api.php的脚本中再次回显数据时将其返回。这是在服务器返回的JSON数据的末尾添加null 下面是我的新auth函数:
protected function auth($parameters) {
if ($this->method == 'POST') {
//need to get the POST data this way because we have the Content-Type header set to application/json, so $_POST will no longer be populated
$rawPostData = file_get_contents('php://input');
//return the data because we will echo it from the api.php script
return $rawPostData;
}else{
$errorMessage = array("error" => "Only accepts POST requests");
return json_encode($errorMessage);
}
}
下面是一个名为api.php的脚本,它响应了结果
<?php
require_once 'MyAPI.class.php';
try {
$API = new MyAPI($_REQUEST, $_SERVER['HTTP_ORIGIN']);
echo $API->processAPI();
} catch (Exception $e) {
echo json_encode(Array('error' => $e->getMessage()));
}
?>
作为请求主体发送的实际JSON负载是什么…?这些症状表明您没有返回有效的JSON。如果指定从服务器返回json,则如果希望能够读取客户端响应,则必须在成功和出错时都返回json。@NeilHibbert,谢谢。对不起,我错漏了。我在JSON Payloads中编辑了我的问题。我猜您在PHP中使用的是不正确的,这导致将PHP错误返回给客户端,该错误不是有效的JSON。我们需要查看实际发送的内容,而不是您打算发送的内容。
protected function auth($parameters) {
if ($this->method == 'POST') {
//need to get the POST data this way because we have the Content-Type header set to application/json, so $_POST will no longer be populated
$rawPostData = file_get_contents('php://input');
//return the data because we will echo it from the api.php script
return $rawPostData;
}else{
$errorMessage = array("error" => "Only accepts POST requests");
return json_encode($errorMessage);
}
}
<?php
require_once 'MyAPI.class.php';
try {
$API = new MyAPI($_REQUEST, $_SERVER['HTTP_ORIGIN']);
echo $API->processAPI();
} catch (Exception $e) {
echo json_encode(Array('error' => $e->getMessage()));
}
?>
var data = {"username":"sarahexample","password":"5f4dcc3b5aa765d61d8327deb882cf99"};
$http({
method: 'POST',
url: 'http://localhost/API/auth',
data : JSON.stringify(data),
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
responseType:'json'
}).then(function successCallback(response) {
console.log('success');
if(response.data.hasOwnProperty('error')){
console.log(response.data.error);
}else{
console.log(response.data.username);
}
}, function errorCallback(response) {
console.log("error");
console.log(response);
});