以下の 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 つのコードがあります 2) 1 つはコメント解除され、もう 1 つはコメントされています 3) コメントされたコードは、コード "dataType: "json にコメントすると機能します"", 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"]
上の正確な配列が返されます。
誰かが私のコードに問題があることを理解できますか?