日期:2014-05-16  浏览次数:20439 次

jquery ajax发送json数据并接收json进行遍历

页面代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<head>
<title>客户端和服务器端使用JSON示例</title>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<style type="text/css">
.style1 {
?width: 568px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
? <div> 用户名
??? <input type="text" name="Text1" id="Text1"/>
??? <br />
??? 密码
??? <input type="text" name="Text2" id="Text2"/>
??? <br />
??? <br />
??? <input type="button" id="btn1" onclick="BtnClick()" value="确定" />
? </div>
? <div id="dd"> sd </div>
? <div>
??? <script type="text/javascript">
function BtnClick() {
var uid = $("#Text1").attr("value");
var pwd = $("#Text2").attr("value");

$.ajax({
url: "server.php",
type: "post",
data: { UserName: uid, Password: pwd },
/*<!--
第一种方法遍历json数据
success: function(data) {
 eval("datas = "+data);
var user = datas.userName;
var pass = datas.password;
$("#dd").html("<h1>用户名:" + user + " 密码:" + pass + "</h1>");
}-->*/

/*第二种方法遍历json数据*/
success: function(data) {
var json =eval("["+data+"]");//这里中间的括号为中括号 使数据类似[{"username":"张三","content":"沙发"}];的格式
$.each(json, function(idx, item) {
var user = item.userName;
var pass = item.password;
$("#dd").html("<h1>用户名:" + user + " 密码:" + pass + "</h1>");
});
}
});
}
</script>
? </div>
</form>
</body>
</html>

?

?

php代码:

?

<?php
$myName =$_REQUEST["UserName"];
$myEmail = $_REQUEST["Password"];
$arr=array(
?userName=>$myName,
?password=>$myEmail
?);
$message = json_encode($arr);
echo $message;
?>

?

?

如果使用getJSON方式遍历数据,如下

$(function(){
??? $("#Button1").bind("click",function(){? ??
?? var data = "name=" + $("#txtname").attr("value");
??????????????? data += "&email=" + $("#txtemail").attr("value");
??????????????? data += "&t1=" + $("#txthomephone").attr("value");
??????????????? data += "&t2=" + $("#txtmobilephone").attr("value");
??????? $.getJSON("server.php",data, function(json){
??????????? $("#name").html(json.Name);
??????????? $("#email").html(json.Email);
??????????? $("#t1").html(json.PhoneNumbers.HomePhone);
??????????? $("#t2").html(json.PhoneNumbers.WorkPhone);
??
?????? });
??? });
});