PHP数组正确的JSON格式


PHP Array correct JSON format

我编写了一个ajax调用,它从.php文件(单击btn_getAnswers时)返回一个数组。到目前为止,对于(来自数据库的)整数数据,这一切都很好。但是,如果我尝试返回填充了三个String的数组,则不会向ajax调用返回任何响应。

Index.html:

<!DOCTYPE html>
<html>
<head>
    <script src="jquery-1.12.3.js"></script> <!-- Import the jquery extension -->
    <script>
        $(document).ready(function(){
            $("#btn_getQuestion").click(function(){
                $.ajax({type :"POST",
                        url: "DBCOMQUESTIONS.php?q=" + $("#input").val(),
                        success: function(result){ //Performs an async AJAX request
                    if(result){
                         $("#output").append(result); //assign the value of the result to the paragraph with the id "output"
                    }
                }});
            }),
            $("#btn_getAnswers").click(function(){
                $.ajax({type :"POST",
                        url: "DBCOMANSWERS.php?q=" + $("#input").val(),
                        dataType:"json",
                        success: function(result){ //Performs an async AJAX request
                    if(result){
                        result.forEach(function(i,v){
                            $("#output").append("<br>" + i);
                        })
                    }
                }});
            });
        });
    </script>
</head>
<body>
<p id="output">This is a paragraph.</p>
<input id="input"/>
<button id="btn_getQuestion">Question</button>
<button id="btn_getAnswers">Answers</button>
</body>
</html>

DBCOMANSWERS.php:

<?php
include("connection.php");  //includes mysqli_connent with database
include("ErrorHandler.php"); //includes error handling function
set_error_handler("ErrorHandler"); //set the new error handler
$q = intval($_GET['q']);
$sql="SELECT * FROM tbl_answers WHERE QID ='".$q."'"; //define sql statement
$query = mysqli_query($con,$sql); // get the data from the db
$result = [];
$i = 0;
while ($row = $query->fetch_array(MYSQLI_NUM)){
    $result[$i] = $row[0];
    $i += 1;
}

mysqli_close($con); // close connection with database
header('Content-Type: application/json');
echo json_encode($result); // return value of $result
?>

如果我将$row[0](或$row[2],$row[3])分配给$result[$i],一切都会正常工作。但如果我将$row[1]分配给$result[$i],返回的"响应"是空的,我会在标准chrome浏览器开发工具的"网络"中查找它。

$row[1]$row[0]与其他列([2][3])之间的唯一区别是,$row[1]的数据类型为varchar,其他列为int/tinyint。

显然,错误出现在.php文件的最后几行。但我不知道我做错了什么。

供您参考:这是关于调用的ajax,当单击id为"btn_getAnswers"的按钮时,它会被触发。

这是我从json_encode 得到的错误

UTF-8字符格式不正确,编码可能不正确

因此,您的数据库似乎没有存储UTF-8字符。因此,在运行json_encode 之前,您需要确保将字符转换为UTF-8

$result = [];
while ($row = $query->fetch_array(MYSQLI_NUM)){
    $result[] = mb_convert_encoding($row[1], 'UTF-8');
}

这应该会将您的字符转换为UTF-8。请注意,这适用于所有编码,而utf8_encode()仅适用于一个

我将把我的评论扩展成一个实际的答案,以便将来的任何人都能很容易地看到。

$row[1]必须包含一些非UTF8字符或数据。

因此,请使用:$result[$i] = utf8_encode($row[0]);

它将被json_encode解析。我自己也遇到过很多次这个问题!