这里介绍一下使用each来循环输出jquery返回的json字符串。
假设:服务器端程序2.asp生成json字符串的代码如下:
<%@ codepage=65001%>
<%
response.Charset="utf-8"
flg=request("flg")
if flg=0 then status=0 else status=1
str="{""status"":"&status&",""postPrice"":[{""Productid"":1,""Productname"": ""手机"",""Price"":25.5,""num"": 1000,""url"":""http://www.baidu.com""},{""Productid"":2,""Productname"": ""相机"",""Price"":75,""num"": 2000,""url"":""http://www.aspbc.com""}]}"
response.write str
%>(鼠标移到代码上去,在代码的顶部会出现四个图标,第一个是查看源代码,第二个是复制代码,第三个是打印代码,第四个是帮助)客户端文件代码如下:
<!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" />
<title>each循环输出jquery返回的json字符串</title>
<style type="text/css">
ol{ border:1px solid #ccc; margin-bottom:10px; padding-top:10px; padding-bottom:15px;padding-right:40px; }
ol li{ border-bottom:1px dotted #ccc; padding-left:5px; line-height:20px; height:20px; }
</style>
<script type="text/javascript" src="http://www.aspbc.com/js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.getJSON("2.asp",{flg: 1, t: Math.random()},
function(json){
var status=json.status;
if(status==0)
{
alert('出错');
}
else
{
var str='';
$.each(json.postPrice,function(i){
m=json.postPrice[i];
str+='<ol> ';
str+='<li>产品ID:'+m.Productid+'</li>';
str+='<li>产品名称:'+m.Productname+'</li>';
str+='<li>价格:'+m.Price+'元</li>';
str+='<li>数量:'+m.num+'</li>';
str+='<li>网址:'+m.url+'</url>';
str+='</ol>';
}
);
$("#div1").html(str);
}
}
);
});
</script>
</head>
<body>
<div id="div1">
</div>
</body>
</html>
(鼠标移到代码上去,在代码的顶部会出现四个图标,第一个是查看源代码,第二个是复制代码,第三个是打印代码,第四个是帮助)运行一下这个html文件,看看效果,是不是得到了json字符串了。
