gpt4 book ai didi

php - 语法错误 : JSON. 解析 : unexpected non-whitespace character after JSON data what is wrong here?

转载 作者:太空宇宙 更新时间:2023-11-03 12:16:47 28 4
gpt4 key购买 nike

我已经搜索了那个错误并查找了很多帖子..但我仍然无法弄清楚这段代码有什么问题:

我的 ajax 调用:

function myCall3() {
$.ajax({
type:"POST",
url:"ajax3.php",
dataType:"json",
success:function(response){
alert(response[0]);
}
});
}

我的 mysql/php 代码:

<?php


// QUERY NEW VINE
$array = array();
$myquery = "SELECT * FROM table1 ORDER BY rand() LIMIT 9";
$result = mysql_query($myquery)
OR die("Error: $myquery <br>".mysql_error());

while($row = mysql_fetch_object($result)){
$currentid = "$row->id";
$currentname = "$row->name";
$currenturl = "$row->url";
$currentimage = "$row->image";
$array[] = array('id'=>$currentid,'url'=>$currenturl,'name'=>$currentname,'image'=>$currentimage);

}

echo json_encode($array);

?>

当我提醒错误时,它说:

SyntaxError: SyntaxError: JSON.parse: unexpected character

最佳答案

您在循环中不断覆盖 $array,然后过早地回显它。

$array =    array('id'=>$currentid,'url'=>$currenturl,'name'=>$currentname,'image'=>$currentimage);

echo json_encode($array);

}

您应该将每一行推送到 $array 变量,然后在循环外进行 json_encode。

$array = array();
$myquery = "SELECT * FROM table1 ORDER BY rand() LIMIT 9";
$result = mysql_query($myquery)
OR die("Error: $myquery <br>".mysql_error());
while($row = mysql_fetch_object($result))
{
$currentid = "$row->id";
$currentname = "$row->name";
$currenturl = "$row->url";
$currentimage = "$row->image";
$array[] = array('id'=>$currentid,'url'=>$currenturl,'name'=>$currentname,'image'=>$currentimage);

}

echo json_encode($array);

那么你的 javascript 回调将需要一个数组,而不是一个对象,即

console.log(response[0]);

注意:您可以直接将 $row 插入您想要的 $array。

关于php - 语法错误 : JSON. 解析 : unexpected non-whitespace character after JSON data what is wrong here?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21814863/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com