$("form").on("submit", function() {
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "ajax2.php", //Relative or absolute path to response.php file
data: data,
success: function (data) {
$("#main_content").slideUp("normal",function(){
$(".the-return").html("<br />JSON: " + data);
//how to alter this part to display data for each record in one div?
});
}
});
return false;
});
我查詢
$statement = $pdo->prepare("SELECT * FROM posts WHERE subid IN (:key2) AND Poscode=:postcode2");
$statement->execute(array(':key2' => $key2,':postcode2'=>$postcode));
// $row = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = array();
while($row = $statement->fetch()) {
array_push($json, array($row['Name'], $row['PostUUID']));
}
header('Content-Type: application/json');
echo json_encode($json);
結果以這種形式顯示當前:
JSON: jack,55421894ab602,test,55439324cc43d
但我想,顯示一個類似:
Name:jack,
Id:55421894ab602
.....and some other info-
Name:test
Id:55439324cc43d
.....and some other info-
這一部分:
$(".the-return").html("<br />JSON: " + data);
我想:data[0];
但是當我這樣做,只有第一條記錄顯示明顯。
我想要的是:
data[0]
本身是一個數組。如何顯示該數組以及在nice html中獲取的其他記錄?
編輯:通過編輯這些代碼,我只能檢索最後一個結果,而不是循環訪問數組。
AJAX 成功:功能(數據){
$("#main_content").slideUp("normal",function(){
//$(".the-return").html("<br />JSON: " + j_data);
for (i = 0; i < data.length; i++) {
$(".the-return").html("<div>Name:" + data[i].name + "<br/>Id:" + data[i].id);
}
console.log(data); // this shows nothing in console,I wonder why?
//alert(j_data);
});
}
PHP
$json = array();
while($row = $statement->fetch()) {
//array_push($json, array($row['Name'], $row['PostUUID']));
array_push($json, array("name" => $row['Name'], "id" => $row['PostUUID']));
}
header('Content-Type: application/json');
echo json_encode($json);
將它們分配到像$ variable = json_decode($ json)這樣的變量中。 $變量將是數組類型,然後您可以輕鬆使用它。 –