下面的 ajax 代码是从 php 接收一个 json 数组。我写的其他细节作为评论:
$.ajax({
type: "POST",
url: "dbtryout2_2.php",
data: datastr,
cache: false,
//dataType: 'json',
success: function (arrayphp) {
//"arrayphp" is receiving the json array from php.
//below code is working where iam displaying the array directly
//This code displays the array in raw format.
$(".searchby .searchlist").append(arrayphp);
}
});
朋友们集中在本节上。现在我将使问题更加清晰和准确:1)成功函数有两个代码 2)一个未注释,另一个已注释 3)如果我注释代码“dataType:”json,则commneted代码有效"", 4) 但是未注释的代码不适用于以下代码当前存在的情况
$.ajax({
type: "POST",
url: "dbtryout2_2.php",
data: datastr,
dataType: "json",
cache: false,
success: function (arrayphp) {
$.each(arrayphp, function (i, v) {
alert(i + "--" + v);
});
/*$(".searchby .searchlist").append(arrayphp);*/
},
error: function (xhr) {
console.log(xhr.responseText);
}
});
下面是负责返回 JSON 数组的 PHP 代码片段:
$arrayphp = array();
//$result is containing the list of albums
//iam one by one taking the album names and assigning it to $row
//then from $element iam pushing the elements in $arrayphp
//after pushing all the elements iam returning the json encoded array to ajax code.
while ($row = mysql_fetch_array($result)) {
$element = $row['cat_name'];
array_push($arrayphp, $element);
}
echo json_encode($arrayphp);
}
返回的数组是专辑名称列表:
["album1", "album2", "album5", "album4", "album6", "album7", "album8", "album9", "album10", "album11"]
确切的上述数组正在返回。
有人会弄清楚我的代码有什么问题吗?