php返回数组给ajax出错

我通过php生成了一个数组,并echo回去,ajax进入error(ajax的datatype设为json),我推断原因在于返回的不是json格式。
求大神帮看看,感谢!
ajax部分:
$("#ricotext").keyup(function(){
$.ajax({
type:"post",
url:"search.php",
dataType:"json",
data:{search:$("#ricotext").val()},
success:function(feedbackdata)
{
console.log(feedbackdata);
console.log(success);
},
error:function(feedbackdata)
{
console.log(feedbackdata);
console.log(error);
},
});
});
php部分:
$servername="localhost";
$username="root";
$password="root";
$dbname="guitartabs";
$search=$_POST["search"];
$conn=newmysqli($servername,$username,$password,$dbname);
//Checkconnection
if($conn->connect_error){
die("连接失败:".$conn->connect_error);
}
$sql="SELECT*FROMtabswherenamelike'%$search%'ORsingerlike'%$search%'";
$result=$conn->query($sql);
$num_results=$result->num_rows;
if($result->num_rows>0){
//生成空数组
$backresults=array();
for($i=0;$i<$num_results;$i++){
$row=$result->fetch_assoc();
//遍历选项并将信息写入数组中
array_push($backresults,array("name"=>$row['name'],"singer"=>$row['singer'],"address"=>$row['address']));
};
//返回给ajax该数组
echo(json_encode($backresults));
}else{
echo"抱歉,本站暂时未收录该乐谱。";
}
$conn->close();
?>
chrome浏览器收到的数据是:
[{"name":"NightWish","singer":"NightWish","address":"uploads\/NightWish.gp5"},{"name":"night","singer":"rico","address":"uploads\/MultiTrack.gp5"},{"name":"nightbar","singer":"ricoq","address":"uploads\/Serenade.gp5"}]
同时console.log打印
readyState:4
error
说明进入了error。我觉得如果echo的是一个json对象应该就能解决问题。请教一下如何解决?
紫衣仙女
浏览 509回答 2
2回答

慕桂英3389331

echo之前加一下headerheader('Content-type:application/json');echo(json_encode($backresults));...

慕神8447489

echo(json_encode($backresults));eixt();或者returnjson_encode($backresults),我自己一般都是return$backresults,然后console.log()就是个对象,也方便处理
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript