JSON位置39的意外标记

时间:2017-03-17 06:29:13

标签: javascript php angularjs json

我有一个字典网络应用程序的php api,

$outp = "";

while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
    if ($outp != "") {$outp .= ",";}
    $outp .= '{"WORD":"'  . $rs["word"] . '",';
    $outp .= '"MEANING":"'   . $rs["definition"]        . '"}';
}
$outp ='{"records":['.$outp.']}';
$conn->close();

echo($outp);

}
else
{


}
?>

并且在angularJS侧,解析功能如下:

$scope.counter = function() {
                    console.log(JSON.stringify(response));

    if($scope.name) {
        $http.get("http://localhost/dictionary/API/search.php?qr="+$scope.name)
            .then(function (response) {
                console.log(JSON.stringify(response.records));
            if(response.data.records=="") {
                queryRes = response.data.records ;
                $scope.word = "";
                $scope.meaning = ""
            } else {

                queryRes = response.data.records ;
                $scope.word = queryRes[0].WORD;
                $scope.meaning = queryRes[0].MEANING;
            }

    });

    }

}

当php api像这样返回单个元素数组JSON时没有错误

{"records":[{"WORD":"Net","MEANING":"വല"}]}

但是当php返回多个元素的数组时,如

{"records":[{"WORD": "End","MEANING": "അറുതി
"},{"WORD": "End","MEANING": "അവസാനം
"},{"WORD": "End","MEANING": "അതിര്‌
"},{"WORD": "End","MEANING": "സീമ
"},{"WORD": "End","MEANING": "പരിസമാപ്‌തി
"},{"WORD": "End","MEANING": "അവസാനഘട്ടം
"},{"WORD": "End","MEANING": "മരണം
"}]}

像这样得到错误

Unexpected token in JSON at position 39 at JSON.parse (<anonymous>)

我认为JSON对象操作存在一些问题。

1 个答案:

答案 0 :(得分:0)

不要通过字符串连接构建JSON;使用json_encode

$records = [];

while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
    $records[] = [
        'WORD' => $rs["word"],
        'MEANING' => $rs["definition"],
    ];
}
$conn->close();

echo json_encode(['records' => $records]);