jquery返回json格式数据来获取每天的天气预报

第一步:静态显示页面

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh-CN">
<head>
<title>itcast</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<script type="text/javascript" src="jquery.js"></script>
<style type="text/css"></style>
</head>
<body>
<table>
  <tr><td><input type="button" name="web" value="今天天气情况" id="content"></td></tr>
</table>
<div id="show" >
    <ul>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
    </ul>
</div>
</body>
</html>

<script type="text/javascript">
    $("#content").click(function(){
        var web="http://m.weather.com.cn/data/101010100.html";  ////google免费提供的天气预报api接口,返回一个weatherinfo对象
        //$.ajax是通过jquery来实现ajax特效,并传了三个参数
        $.ajax({
            type:"GET",
            url:"content.php",
            data:"url="+web,
            success:function(msg){
                var obj = eval('('+msg+')'); //eval()是把后台传过来的json格式数据转换了一个jquery对象
                //下面是要显示的一些内容,由于json格式返回的结果集中有点像二维数组的样式,因此下面内容的显示要这样显示,这里的内容只是显示一部分,当然你也可以显示更多的内容(方法:加li,要是读者不清楚如何加时可以打印obj这个对象,你看它的返回值就明白如何加了)
                $("#show li").eq(0).html(obj['weatherinfo']['city']);
                $("#show li").eq(1).html(obj['weatherinfo']['date_y']);
                $("#show li").eq(2).html(obj['weatherinfo']['week']);
                $("#show li").eq(3).html(obj['weatherinfo']['temp1']);
                $("#show li").eq(4).html(obj['weatherinfo']['img_title4']);
                $("#show li").eq(5).html(obj['weatherinfo']['index_d']);
            }
        });
    });
</script>

第二步:后台接收并返回结果页面

<?php
$url = $_GET['url'];  //获取ajax传过来的地址
$rs=file_get_contents($url); //获取这个地址里内容,并赋给一个变量,最后输出。
echo $rs;
?>

原文地址:https://www.cnblogs.com/hulan/p/2751285.html