【发布时间】:2018-03-10 12:07:03
【问题描述】:
尝试向我的 PHP API 发出 ajax 请求(使用 Angularjs)时出现以下错误。
SyntaxError: Unexpected token n in JSON at position 24
如果有任何帮助,我将不胜感激。谢谢
这是我的 Angular JS 代码:
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 身份验证函数。
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";
}
}
在我的 PHP API 中,我有以下标头(取出后一切正常,但我希望它与标头一起使用)。
header("Content-Type: application/json");
我尝试在上面的标题中留下,并在 ajax 请求中添加contentType: 'application/json',如下所示(但这并没有解决 JSON 错误):
$http({
method: 'POST',
url: 'http://localhost/API/auth',
contentType: 'application/json',
data : JSON.stringify(data)
}).then(function successCallback(response) {
console.log(response);
}, function errorCallback(response) {
console.log(response);
});
在控制台的网络选项卡中:
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"
【问题讨论】:
-
您作为请求正文发送的实际 JSON 有效负载是什么...?
-
症状表明您没有返回有效的 json。如果您指定从服务器返回 json,如果您希望能够读取响应客户端,则必须在成功和错误时都返回 json。
-
@NeilHibbert 谢谢。抱歉,我不小心把它漏掉了。我编辑了在 JSON 有效负载中添加的问题
-
我的猜测是您在 PHP 中对
header的使用不正确,这导致向客户端返回 PHP 错误,该错误不是有效的 JSON。 -
我们需要查看实际发送的内容,而不是您打算发送的内容。
标签: javascript php angularjs json content-type