【getJSON取数据】
data为getJSON的参数,是ajax返回的json值,然后对data进行循环(each)取出想要的值。
第一步:
json用json后缀文件保存,内容为: // 不要在前面加“var a=”这样的字样
[{
"name":"王俊",
"sex":"男",
"email":"673695560@qq.com"
}
,
{
"name":"李明",
"sex":"女",
"email":"321231312@qq.com"
}]
第二步:
<body>
<input type="button" id="f">
<div id="s"></div>
<script type="text/javascript" src="jquery-1.5.1.js"> </script>
<script type="text/javascript">
$("#f").click( function( ){
$.getJSON("22.json",function(data){
var str=""; // 这步初始为空的声明不能少,否则str未定义
$.each(data,function( key,info ){ // key和info的名字随便取
str+="姓名:"+info["name"]+"<br>";
str+="性别:"+info["sex"]+"<br>";
str+="邮箱:"+ info["email"]+"<hr>";
})
$("#s").html(str); // 注意位置,要写在循环之外
});
})
</script>
</body>
【getScript取数据】
js文件内容: // 注意不要在首尾加什么<script type="text/javascript"></script>
var data=
[{
"name":"王俊",
"sex":"男",
"email":"673695560@qq.com"
}
,
{
"name":"李明",
"sex":"女",
"email":"321231312@qq.com"
}];
var str="";
$.each(data,function( ){
str+="姓名"+this["name"]+"<br>";
str+="性别"+this["sex"]+"<br>";
str+="邮箱"+this["email"]+"<br>";
})
$("#s").html(str);
html代码:
<body>
<input type="button" value="ajax提交" id="f">
<div id="s"></div>
<script type="text/javascript" src="jquery-1.5.1.js"> </script>
<script type="text/javascript">
$("#f").click( function( ){
$.getScript("33.js");
})
</script>
</body>
注意$.getJSON与$.getScript在写法上有所不同,前者的循环是在html中进行的,后者的循环是在js文件中直接写好的。