<!doctype html> <html lang="en"> <head>//html页面,往后台发送数据,并接收处理 <meta charset="UTF-8"> <title>Document</title> <script type="text/javascript" src="jquery-1.8.2.min.js"></script> </head> <body> <center> <input type="text" name="address"/><button>显示天气</button> <div></div> </center> </body> </html> <script> $(function(){ $("button").click(function(){ var address=$("input").val(); $.ajax({ type:"get", url:"http://localhost/phone.php", data:{ address:address }, dataType:"json", success:function(data){ var str=""; str+="<table border='1'>"; str+="<tr>"; str+="<th>日期</th>"; str+="<th>星期</th>"; str+="<th>农历</th>"; str+="<th>白天</th>"; str+="<th>夜晚</th>"; str+="<th>气温</th>"; str+="</tr>"; //alert(data..); for(var i=0;i<data.length;i++){ str+="<tr>"; str+="<td>"+data[i].date+"</td>"; str+="<td>"+data[i].week+"</td>"; str+="<td>"+data[i].nongli+"</td>"; //for(var s=0;s<data[i].info.length();s++){ str+="<td>"+data[i].info.day[1]+","+data[i].info.day[4]+"</td>"; str+="<td>"+data[i].info.night[1]+","+data[i].info.night[4]+"</td>"; str+="<td>D"+data[i].info.day[2]+",N"+data[i].info.night[2]+"</td>"; //} str+="</tr>"; } str+="</table>"; $("div").html(str); } }) }) }) </script>
//PHP页面,在后台处理请求获取天气情况,并发送至前台拼接展示。
<?php header("content-type:text/html;charset=utf-8"); $address=$_GET['address']; //$address="北京"; $url="http://op.juhe.cn/onebox/weather/query?cityname={$address}&key=cd36d5186727ed91dcd087760093af0f&dtype="; $str=file_get_contents($url); //$str=simplexml_load_file($url); $arr = json_decode($str,true); unset($arr['reason']); unset($arr['error_code']); unset($arr['result']['data']["realtime"]); unset($arr['result']['data']["life"]); unset($arr['result']['data']["pm25"]); unset($arr['result']['data']["jingqu"]); unset($arr['result']['data']["date"]); unset($arr['result']['data']["isForeign"]); foreach($arr as $key=>$val){ foreach($val as $k=>$v){ foreach($v as $kk=>$vv){ foreach($vv as $kkk=>$vvv){ $list[]=$vvv; } } } } echo json_encode($list); ?>