如何在html页面形成json数组,如何在html中正确显示json数据数组?

这篇博客讨论了如何在AJAX提交表单后,从PHP返回并显示多个JSON记录的问题。作者遇到了只显示第一条记录的困扰,并尝试通过循环遍历数据来解决,但未能成功。目前的代码中,JSON数据以Name和Id的形式返回,但作者希望以更友好的HTML格式显示所有记录。博客中还包含了PHP和AJAX的代码示例,展示了数据获取和处理的过程。
摘要由CSDN通过智能技术生成

$("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("
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("
JSON: " + data);

我想:data[0]; 但是当我这样做,只有第一条记录显示明显。

我想要的是:

data[0]本身是一个数组。如何显示该数组以及在nice html中获取的其他记录?

编辑:通过编辑这些代码,我只能检索最后一个结果,而不是循环访问数组。

AJAX 成功:功能(数据){

$("#main_content").slideUp("normal",function(){

//$(".the-return").html("
JSON: " + j_data);

for (i = 0; i < data.length; i++) {

$(".the-return").html("

Name:" + data[i].name + "
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);

2015-05-06

sherly

+0

将它们分配到像$ variable = json_decode($ json)这样的变量中。 $变量将是数组类型,然后您可以轻松使用它。 –

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值