您好,我对编程有点陌生,我正尝试使用ajax,并希望从此php中获取值,但无法使其正常工作
$userID = $_SESSION['id'];
$query = "SELECT * from ipcr where userID = '".$userID."'";
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($result)) {
$current_id = $row['id'];
$current_details = $row['details'];
$current_dateCreated = $row['dateCreated'];
$current_ipcrCode = $row['ipcrCode'];
$current_employeeNumber = $row['employeeNumber'];
$array = array(
'id'=>$current_id,
'details' => $current_details,
'dateCreated' => $current_dateCreated,
'ipcrCode' => $current_ipcrCode,
'employeeNumber' => $current_employeeNumber
);
echo json_encode($array);
}
但我不断收到错误消息:
SyntaxError:JSON中位置173上的意外令牌<< / p>
当我尝试验证我的json时 this error
这是php回显的实际输出。
{"id":"21836","details":"Details here","dateCreated":"2018-08-01 14:25:28","ipcrCode":"22703","employeeNumber":"140010663"}
{"id":"21837","details":"details here","dateCreated":"2018-08-01 14:25:57","ipcrCode":"22703","employeeNumber":"140010663"}
我使用json_encode的方式有问题吗?看来我呼应的格式是错误的。
这也是我的脚本的样子
function get_ipcr() {
var userID = <?php echo $_SESSION['id']; ?>;
$.ajax({
type: "POST",
url: "../includes/php/load_ipcr.php",
dataType: "json",
success: function(results) {
alert("success");
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
答案 0 :(得分:4)
问题是您正在循环回显JSON对象。这样会导致{valid JSON}{valid JSON}
之类的东西,它不是有效的JSON。
您可以通过以下方式解决此问题:
$employees = array();
while ($row = mysqli_fetch_assoc($result)) {
$current_id = $row['id'];
$current_details = $row['details'];
$current_dateCreated = $row['dateCreated'];
$current_ipcrCode = $row['ipcrCode'];
$current_employeeNumber = $row['employeeNumber'];
// Record into employees array.
$employees[] = array(
'id'=>$current_id,
'details' => $current_details,
'dateCreated' => $current_dateCreated,
'ipcrCode' => $current_ipcrCode,
'employeeNumber' => $current_employeeNumber
);
}
echo json_encode($employees);
答案 1 :(得分:1)
欢迎来到stackoverflow!
您将要从不同的评论/答案中听到几件事,我建议您听听他们的声音-似乎不堪重负,或者像“信息太多”一样-但请相信我,我们都在这里为您提供帮助!
问题的答案
将 entire JSON字符串烘烤到单个数组(数组的数组)中,而不是在循环中多次回显JSON字符串。
其他提示
另外,作为提示,通过分配所有变量($current_id = $row['id']
等),您可以自己进行更多输入。您可以直接直接使用$row['id']
……在下面,您可以看到我展示了一种简化代码的方法:
// shorthand version of $array = array()
$array = [];
while ($row = mysqli_fetch_assoc($result)) {
// don't bother assigning $row values to a series of variables
// removed all the lines like the next one....
// $current_id = $row['id'];
// push this record onto the array of arrays....
$array[] = [
// assign the array values directly from $row
'id' =>$row['id'],
'details' => $row['details'],
'dateCreated' => $row['dateCreated'],
'ipcrCode' => $row['ipcrCode'],
'employeeNumber' => $row['employeeNumber']
];
}
echo json_encode($array);
最后,最重要
请,请-不要写这样的查询语句。它对SQL注入攻击开放,这是一个严重的问题。