<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>新建网页</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<script type="text/javascript">
function f1(){
//通过ajax请求json信息回来
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState==4){
//alert(typeof xhr.responseText); //string json信息是字符串形式回来的
eval("var jn_info="+xhr.responseText); //eval()将字符串当成代码来执行。
console.log(jn_info.city);
console.log(jn_info.temp);
console.log(jn_info.wind);
}
}
xhr.open('get','./04.php');
xhr.send(null);
}
/*
//字符串形式回来的json信息变为对象object(将字符串两端的引号去掉)
var dog = "{name:'wangcai',weight:50}"; //去掉两端的引号
//字符串当做表达式运行eval()
eval("var wolf="+dog); //"var wolf={name:'wangcai',weight:50}"
alert(wolf);//object Object
*/
</script>
</head>
<body>
<h2>静态网站页面通过javascript实现json接收和处理</h2>
<input type="button" value="触发" οnclick="f1()" />
</body>
</html>
04.php(服务器端(返回JSON信息)):
<?php
$weather = array('city'=>'beijing','temp'=>'15','wind'=>'south');
echo json_encode($weather);