【问题标题】:Why am I getting a JSON error related to content type in my ajax request?为什么我在 ajax 请求中收到与内容类型相关的 JSON 错误?
【发布时间】: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


【解决方案1】:

正确的做法是在回显之前检查您的 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;

【讨论】:

    【解决方案2】:

    我发现了错误发生的原因。有几件事情的组合。

    首先,我犯了一个愚蠢的错误,我不小心重复了两次数据:

    我有一个名为 MyAPI.php 的类,其中包含 auth 方法。当我应该返回数据时,我正在从这里回显数据,因为它在另一个名为 api.php 的脚本中再次得到回显。这是在服务器返回的 JSON 数据的末尾添加一个 null。

    这是我的新身份验证功能:

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

    现在是另一件事。我需要将 responseType:'json' 添加到 ajax 请求中,如下所示:

    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);
    
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-10
      • 2012-10-04
      • 2016-03-30
      相关资源
      最近更新 更多