基于PHP的AJAX学习笔记(教程)

本文转载自:http://www.softeng.cn/?p=107

这是本人在学习ajax过程所做的笔记,通过本笔记的学习,可以完成ajax的快速入门。本笔记前端分别使用原生态的javascript语言和jQuery语言,服务器端使用PHP语言。

 

一、基础知识
1、创建XMLHttpRequest对象(不同的浏览器获取XMLHttpRequest方法不同)
//创建ajax引擎
function getXMLHttpRequest() {
        var xmlhttp;
        try {
                //Firefox,Opera 8.0+, Safari
                xmlhttp = new XMLHttpRequest();
        }catch (e) {
                //Internet Explorer
                try {
                        xmlhttp = new ActiveXObject("Msxml12.XMLHTTP");
                }catch (e) {
                        try {
                                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                        }catch (e) {
                                alert("您的浏览器不支持AJAX!");
                                return false;
                        }
                }
        }
        return xmlhttp;
}
2、调用XMLHttpRequest对象的open(method,url,async)方法,打开链接。open方法的三个参数:第一个为请求类型,GETPOST;第二个参数为所要请求的URL地址;第三个参数为是否采用异步机制,true(异步)或false(同步)
3、调用XMLHttpRequest对象的
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded")方法添加HTTP头,这个方法多用在以POST方法提交数据时。
4、调用XMLHttpRequest对象的onreadystatechange属性,指定回调函数
5、调用XMLHttpRequest对象的send()方法,发送请求,在GET方式中,通常将所要传递的参数显示的加载url后面,在POST方式中,将数据作为参数传入,两个参数之间用&分割,例如:xmlhttp.send("key1=value1&key2=value2");
6、在指定的回调函数里面取出服务器返回的值,回调函数会被触发四次,因为状态发生了四次变化,可以通过判断readyState属性的值判断状态,然后根据返回信息的格式,取出返回的数据
7、当以POST方式请求时,除了send()的参数不同外,还需要设置响应头部的信息setRequestHeader("Content-Type","application/x-www-form-urlencoded");
8、处理返回格式是xml的数据处理时,在服务端要用header("Content-Type:text/xml;charset=utf-8");语句设置返回格式为xml
9、在返回xml数据格式时,服务器端返回的是xml对象,通过XML DOM解析
10、在返回json数据格式时,服务器端返回的是一个字符串,需要调用javascripteval()函数来执行,并返回真正的json对象
11eval函数的具体使用:var json_obj = eval(“(”+xmlhttp.responseText+”)”);
12json的几种格式:
  
基本格式
  
例子
“{属性名:属性值,属性名:属性值……}”
<script type=”text/javascript”>
  
var dog = {“name”:”小明”,”age”:”18”,””:””……}
  
alert(dog.name);
  
alert(dog.age);
  
</script>
[
  
{名称1:值1,名称2:值2,……}
  
{名称1:值1,名称2:值2,……}
  
<script  type="text/javascript">
  
var dog = [
  
{"name":"小名","age":"3"},
  
{"name":"小花","age":"4"}
   
 
  
for(var i = 0; i < dog.length; i++) {
  
         alert(dog.name);
  
         alert(dog.age);
  
}
  
</script>
扩展格式
<script language="JavaScript">
  
var people ={
  
"programmers":
  
[
  
   {"firstName": "Brett", "email":  "brett@newInstance.com" },
  
   {"firstName": "Jason", "email":  "jason@servlets.com" }
   
};
  
window.alert(people.programmers[0].firstName);
  
window.alert(people.programmers[1].email);
  
</script>
扩展格式
<script  language="JavaScript">
  
     var people ={
  
            "programmers": [
  
            { "firstName":  "Brett", "email": "brett@newInstance.com" },
  
            { "firstName":  "Jason",  "email":  "jason@servlets.com" },
  
            { "firstName":  "Elliotte", "lastName":"Harold",  "email": "elharo@macfaq.com" }
  
            ],
  
           "authors": [
  
            { "firstName":  "Isaac",  "genre":  "science fiction" },
  
            { "firstName":  "Tad", "genre": "fantasy" },
  
            { "firstName":  "Frank",  "genre":  "christian fiction" }
  
            ],
  
           "musicians": [
  
            { "firstName":  "Eric",   "instrument": "guitar" },
  
            { "firstName":  "Sergei", "instrument": "piano" }
  
            ]};
  
     window.alert(people.programmers[1].firstName);
  
     window.alert(people.musicians[1].instrument);
  
</script>
  
 
扩展格式
<script  language="JavaScript">
  
       var people ={
  
              "username":"mary",
  
             "age":"20",
  
              "info":{"tel":"1234566","celltelphone":788666},
  
             "address":[
  
                      {"city":"beijing","code":"1000022"},
  
                      {"city":"shanghai","code":"2210444"}
   
         };
  
       window.alert(people.username);
  
       window.alert(people.info.tel);
  
       window.alert(people.address[0].city);
  
</script>
  
 
13、三种格式的对比
  
文本格式
  
1、数据量小,但不需要和其他程序通信时较为适用
XML格式
1、格式通用能够和其他应用程序通信
  
2、当远程应用程序未知的时候是首选
JSON格式
1、原生态数据,描述能力强,数据结构简单
  
2、格式要求严格
  
3、元素的数据类型可以是intstringfloatbooleanarrayobject等基本数据格式
  
4eval函数有一定的风险
  
5、如果无特殊需求推荐使用

14、如果我们的代码比较复杂,可以使用file_put_contents函数,将数据输出到日志文件进行查看,调试


二、示例程序
1、使用ajax完成无刷新的注册界面
1.1两个页面,注册页面和注册处理页面
1.2当用get方式提交数据(URL)的时候,如果两次提交的数据完全相同,则并不是真的发送请求,而是从缓存中取出上次的数据,碰到这样的情况,有两种方式解决:
第一种,在客户端可以通过添加时间戳等方式,迫使每次提交的数据都有不同,避免浏览器的过度智能所造成的页面数据不更新的情况;
第二种,在服务器端禁用缓存的方式,在服务器端加上header(“Cache-Control:no-cache”);
1.3如果想实现在输入框中边输入,边验证的效果,需要给输入框加上onkeyup事件的处理
1.4返回文本方式的源代码
index.php(注册页面)完整代码
<html>
<head>
<title>用户注册</title>
<script type="text/javascript">
var xmlhttp = null;
function $(id) {
        return document.getElementById(id);
}

//创建ajax引擎
function getXMLHttpRequest() {
        var xmlhttp;
        try {
                //Firefox,Opera 8.0+, Safari
                xmlhttp = new XMLHttpRequest();
                //alert("Firefox,Opera 8.0+, Safari");
        }catch (e) {
                //Internet Explorer
                try {
                        //Internet Explorer 6.0+
                        xmlhttp = new ActiveXObject("Msxml12.XMLHTTP");
                        //alert("Internet Explorer 6.0+");
                }catch (e) {
                        try {
                                //Internet Explorer 5.5+
                                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                                //alert("Internet Explorer 5.5+");
                        }catch (e) {
                                alert("您的浏览器不支持AJAX!");
                                return false;
                        }
                }
        }
        return xmlhttp;
}

//验证用户名是否存在
function checkName() {
        xmlhttp = getXMLHttpRequest();

        //怎么判断创建是否成功
        if (xmlhttp) {
                //通过xmlhttprequest对象,发送请求到服务器
                //第一个参数表示请求的方式get或者post
                //第二个参数指定URL,其本质仍然是HTTP请求
                //第三个参数指定是否采用异步机制
                /*
                //以get方式发送
                var url = "/ajax/register/register.php?datetime="+new Date()+"&username="+$("username").value;
                xmlhttp.open("get", url, true);//打开请求
                //指定回调函数,指定的函数名一定不要带括号
                xmlhttp.onreadystatechange = chuli;
                //发送请求
                xmlhttp.send();
                */
                //以post方式发送
                var url = "/ajax/register/register.php";
                var data = "username="+$("username").value;
                xmlhttp.open("post", url, true);//打开请求
                //下面这句话是post方式发送时必须要
                xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                //指定回调函数,指定的函数名一定不要带括号
                xmlhttp.onreadystatechange = chuli;
                //发送请求
                xmlhttp.send(data);
        }
}


//处理函数
function chuli() {
        //alert("处理函数被调用"+xmlhttp.readyState);
        //取出从服务器返回的数据
        if (xmlhttp.readyState == 4) {
                //取出值,根据返回信息的格式而定
                //window.alert("服务器返回值为:"+xmlhttp.responseText);

                $("myres").value = xmlhttp.responseText;
        }
}
</script>
</head>
<body>
<form action="#" method="post">
用户姓名:<input type="text" name="username1" id="username" onkeyup="checkName();" />
<input type="button" onclick="checkName();" value="验证用户名" />
<input style="border-width: 0;color: red" type="text" id="myres" /><br>
用户密码:<input type="password" name="password"/><br>
电子邮箱:<input type="text" name="email"/><br>
<input type="submit" value="用户注册" />
</form>
<br>
<form action="#" method="post">
用户姓名:<input type="text" name="username" />
<input style="border-width: 0;color: red" type="text" id="myres" /><br>
用户密码:<input type="password" name="password"/><br>
电子邮箱:<input type="text" name="email"/><br>
<input type="submit" value="用户注册" />
</form>
</body>
</html>

register.php(注册处理页面)

 

<?php
//设置返回的格式
header("Content-Type:text/html;charset=utf-8");
//设置禁用缓存
header("Cache-Control:no-cache");
//接受数据
//$username = $_GET['username'];
$username = $_POST['username'];
if ($username == "wuhaohua") {
        echo "用户名不可用";
}else {
        echo "用户名可用";
}
?>

 

1.5返回xml格式的源代码
index.php(注册页面)核心修改代码
<script type="text/javascript">
//处理函数
function chuli() {
        //alert("处理函数被调用"+xmlhttp.readyState);
        //取出从服务器返回的数据
        if (xmlhttp.readyState == 4) {
                //取出值,根据返回信息的格式而定
                //取出XML文本格式
                //获取msg节点
                var msg = xmlhttp.responseXML.getElementsByTagName("msg");
                //取出msg节点的值
                //msg[0]表示取出第一个msg节点
                //msg[0]msg[0].childNodes[0]表示取出msg节点的第一个子节点
                var msg_val = msg[0].childNodes[0].nodeValue;
                $("myres").value = msg_val;
        }
}
</script>

register.php(注册处理页面)

 

<?php
//设置返回的格式
header("Content-Type:text/xml;charset=utf-8");
//设置禁用缓存
header("Cache-Control:no-cache");
//接受数据
$username = $_POST['username'];

//返回xml格式数据
$info = "";
if ($username == "wuhaohua") {
        $info = "<res><msg>用户名不可用,对不起</msg></res>";
}else {
        $info = "<res><msg>用户名可用,恭喜</msg></res>";
}
echo $info;
?>

 

1.5返回json格式的源代码
index.php(注册页面)核心修改代码
//处理函数
function chuli() {
        //alert("处理函数被调用"+xmlhttp.readyState);
        //取出从服务器返回的数据
        if (xmlhttp.readyState == 4) {
                //取出值,根据返回信息的格式而定
                //取出json文本格式
                var msg = xmlhttp.responseText;
                //将字符串转换成json对象
                var json_obj = eval("("+msg+")");
                //取出json对象的属性
                $("myres").value = json_obj.res;
        }
}

register.php(注册处理页面)

 

<?php
//设置返回的格式
header("Content-Type:text/html;charset=utf-8");
//设置禁用缓存
header("Cache-Control:no-cache");
//接受数据
$username = $_POST['username'];

//返回xml格式数据
$info = "";
if ($username == "wuhaohua") {
        $info = '{"res":"该用户名不可用"}';//json格式的字符串
}else {
        $info = '{"res":"该用户名可用"}';//json格式的字符串
}
echo $info;
?>

 

2、省市联动
2.1根据选择的上级行政区域,动态加载下一级行政区域并显示,比如选择省之后,动态加载该省的所有市,依次类推
2.2两个页面,一个下拉列表界面,一个信息处理界面

 

2.3返回XML形式数据的源代码
index.php(下拉列表界面)
<html>
<head>
<title>省市联动</title>
<meta content="text/html; charset=UTF-8" http-equiv="content-type" />
<script type="text/javascript">
var xmlhttp;

function $(id) {
        return document.getElementById(id);
}

//创建ajax引擎
function getXMLHttpRequest() {
        var xmlhttp;
        try {
                //Firefox,Opera 8.0+, Safari
                xmlhttp = new XMLHttpRequest();
                //alert("Firefox,Opera 8.0+, Safari");
        }catch (e) {
                //Internet Explorer
                try {
                        //Internet Explorer 6.0+
                        xmlhttp = new ActiveXObject("Msxml12.XMLHTTP");
                        //alert("Internet Explorer 6.0+");
                }catch (e) {
                        try {
                                //Internet Explorer 5.5+
                                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                                //alert("Internet Explorer 5.5+");
                        }catch (e) {
                                alert("您的浏览器不支持AJAX!");
                                return false;
                        }
                }
        }
        return xmlhttp;
}


function getCity() {
        var url = "/ajax/provinces/provinces.php";
        var data = "province="+$("province").value;
        xmlhttp = getXMLHttpRequest(); // 获取对象
        xmlhttp.open("POST", url, true);// 打开请求
        xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");//设置报文头部
        xmlhttp.onreadystatechange = chuliCity;// 设置回调函数
        xmlhttp.send(data); //发送数据
}

function chuliCity() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                //服务器处理完成并且成功
                //删除select中所有的项
                $('city').options.length = 0;
                //添加默认项
                //var defaultoption = document.createElement("option");
                //defaultoption.value = "";
                //defaultoption.innerText = "---市---";
                //$('city').appendChild(defaultoption);
                var cities = xmlhttp.responseXML.getElementsByTagName("city");
                for (var i = 0; i < cities.length; i++) {
                        var city = cities[i].childNodes[0].nodeValue;
                        //创建option结点
                        var myoption = document.createElement("option");
                        myoption.value = city;
                        myoption.innerText = city;
                        //添加option结点
                        $('city').appendChild(myoption);
                }
        }
}

</script>
</head>
<body>
        <select id="province" onchange="getCity();">
                <option value="">---省---</option>
                <option value="sichuan">四川</option>
                <option value="gansu">甘肃</option>
        </select>
        <select id="city" onchange="getCountry();">
                <option value="">---市---</option>
        </select>
        <select id="country">
                <option value="">---县---</option>
        </select>
</body>
</html>

provinces.php(信息处理页面)

 

<?php
//设置返回的格式
header("Content-Type:text/xml;charset=utf-8");
//设置禁用缓存
header("Cache-Control:no-cache");

//接收客户端数据
$province = $_POST['province'];
$info="";
if ($province == "sichuan") {
        $info="<province><city>成都</city><city>广元</city><city>绵阳</city></province>";
}elseif ($province == "gansu") {
        $info="<province><city>兰州</city><city>武威</city><city>酒泉</city></province>";
}else {
        $info="<province><city>---市---</city></province>";
}

echo $info;
?>

 

2.4返回JSON数据格式(前台用JQueryload方式提交)
index.php(下拉列表页)
<html>
<head>
<title>省市联动</title>
<meta content="text/html; charset=UTF-8" http-equiv="content-type" />
<script type="text/javascript" src="../js/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(function (){
        $('#province').change(function (){
                //id为province的标签的onchange事件被触发
                $('#city').load("/ajax/provinces/provinces.php", {province:$('#province option:selected').val()}, function(responseText, textStatus, XMLHttpRequest) {
                        //发送ajax请求并接收回传值
                        if (textStatus == "success") {
                                //请求成功
                                var msg_obj = eval("("+responseText+")");
                                for (var i = 0; i < msg_obj.length; i++) {
                                        //alert("<option value='"+msg_obj[i].city_value+"'>"+msg_obj[i].city_name+"</option>");
                                        var $myoption = $("<option value=\""+msg_obj[i].city_value+"\">"+msg_obj[i].city_name+"</option>");
                                        $("#city").append($myoption);
                                }
                        }
                        });
                });
});
</script>
</head>
<body>
        <select id="province">
                <option value="">---省---</option>
                <option value="sichuan">四川</option>
                <option value="gansu">甘肃</option>
        </select>
        <select id="city" onchange="getCountry();">
                <option value="">---市---</option>
        </select>
        <select id="country">
                <option value="">---县---</option>
        </select>
</body>
</html>

provinces.php(信息处理页)

 

<?php
//设置返回的格式
header("Content-Type:text/html;charset=utf-8");
//设置禁用缓存
header("Cache-Control:no-cache");

//接收客户端数据
$province = $_POST['province'];
// echo $province;
$info="";
if ($province == "sichuan") {
        $info='[{"city_value":"chengdu","city_name":"成都"},{"city_value":"guangyuan","city_name":"广元"},{"city_value":"mianyang","city_name":"绵阳"}]';
}elseif ($province == "gansu") {
        $info='[{"city_value":"lanzhou","city_name":"兰州"},{"city_value":"wuwei","city_name":"武威"},{"city_value":"jiuquan","city_name":"酒泉"}]';
}else {
        $info='[{"city_value":"","city_name":"---市---"}]';
}

echo $info;
?>

 

2.5返回XML数据格式(前台用JQuery$.get()方式提交)
index.php
<html>
<head>
<title>省市联动</title>
<meta content="text/html; charset=UTF-8" http-equiv="content-type" />
<script type="text/javascript" src="../js/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(function (){
        $('#province').change(function (){
                //id为province的标签的onchange事件被触发
                $.get("/ajax/provinces/provinces.php", {province: $("#province option:selected").val()}, function (data, textStatus) {
                        $("#city").empty();
                        $(data).find("city").each(function() {
                                var $myoption = $("<option value\""+$(this).attr("name")+"\">"+$(this).text()+"</option>");
                                $("#city").append($myoption);
                        });
                });
        });
});
</script>
</head>
<body>
        <select id="province">
                <option value="">---省---</option>
                <option value="sichuan">四川</option>
                <option value="gansu">甘肃</option>
        </select>
        <select id="city" onchange="getCountry();">
                <option value="">---市---</option>
        </select>
        <select id="country">
                <option value="">---县---</option>
        </select>
</body>
</html>

provinces.php

 

<?php
//设置返回的格式
header("Content-Type:text/xml;charset=utf-8");
//设置禁用缓存
header("Cache-Control:no-cache");

//接收客户端数据
$province = $_GET['province'];
// echo $province;
$info="";
if ($province == "sichuan") {
        //$info='[{"city_value":"chengdu","city_name":"成都"},{"city_value":"guangyuan","city_name":"广元"},{"city_value":"mianyang","city_name":"绵阳"}]';
$info = "<province><city name='chengdu'>成都</city><city name='guangyuan'>广元</city><city name='mianyang'>绵阳</city></province>";
}elseif ($province == "gansu") {
        //$info='[{"city_value":"lanzhou","city_name":"兰州"},{"city_value":"wuwei","city_name":"武威"},{"city_value":"jiuquan","city_name":"酒泉"}]';
        $info = "<province><city name='lanzhou'>兰州</city><city name='wuwei'>武威</city><city name='jiuquan'>酒泉</city></province>";
}else {
        //$info='[{"city_value":"","city_name":"---市---"}]';
        $info = "<province><city name=''>---市---</city></province>";
}

echo $info;
?>

 

2.6JSON数据格式(前台用JQuery$.post()方式提交)
index.php
<html>
<head>
<title>省市联动</title>
<meta content="text/html; charset=UTF-8" http-equiv="content-type" />
<script type="text/javascript" src="../js/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(function (){
        $('#province').change(function (){
                //id为province的标签的onchange事件被触发
                $.post("/ajax/provinces/provinces.php", {province:$("#province option:selected").val()}, function (data, textStatus) {
                        $("#city").empty();
                        for (var i = 0; i < data.length; i++) {
                                var $myoption = $("<option value='"+data[i].city_value+"'>"+data[i].city_name+"</option>");
                                $("#city").append($myoption);
                        }
                }, "json");
        });
});
</script>
</head>
<body>
        <select id="province">
                <option value="">---省---</option>
                <option value="sichuan">四川</option>
                <option value="gansu">甘肃</option>
        </select>
        <select id="city" onchange="getCountry();">
                <option value="">---市---</option>
        </select>
        <select id="country">
                <option value="">---县---</option>
        </select>
</body>
</html>

provinces.php

 

<?php
//设置返回的格式
header ( "Content-Type:text/html;charset=utf-8" );
//设置禁用缓存
header ( "Cache-Control:no-cache" );

//接收客户端数据
$province = $_REQUEST ['province'];
// echo $province;
$info = "";
if ($province == "sichuan") {
        $info='[{"city_value":"chengdu","city_name":"成都"},{"city_value":"guangyuan","city_name":"广元"},{"city_value":"mianyang","city_name":"绵阳"}]';
//         $info = "<province><city name='chengdu'>成都</city><city name='guangyuan'>广元</city><city name='mianyang'>绵阳</city></province>";
} elseif ($province == "gansu") {
        $info='[{"city_value":"lanzhou","city_name":"兰州"},{"city_value":"wuwei","city_name":"武威"},{"city_value":"jiuquan","city_name":"酒泉"}]';
//         $info = "<province><city name='lanzhou'>兰州</city><city name='wuwei'>武威</city><city name='jiuquan'>酒泉</city></province>";
} else {
        $info='[{"city_value":"","city_name":"---市---"}]';
//         $info = "<province><city name=''>---市---</city></province>";
}

echo $info;
?>

 

3、天气预报查询
3.1使用中国国家气象局天气预报信息接口查询全国各地的天气情况
3.2使用ajax方式动态加载省市信息,异步无刷新查询天气预报
3.3使用php发送跨域请求,获取国家气象局信息接口返回的json信息,并将其做为ajax请求响应报文返回给前台页面
3.4源代码
index.php(信息展示页)
<!DOCTYPE unspecified PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>天气预报查询</title>
<meta content="text/html; charset=utf-8">
<script type="text/javascript" src="../js/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="weather_forecast.js"></script>
<style type="text/css">
table.weather {
        table-layout: fixed;
        text-align: center;
}

table.index {
        width: 580px;
}

body {
        font-family: 仿宋;
}

select {
        width: 80px;
}
</style>
</head>
<body>
        <center>
                <select id="province">
                        <option value="">---省---</option>
<?php
//打开数据库
$connect = mysql_connect ( "localhost", "root", "" );
mysql_select_db ( "weather_forecast" );
mysql_query ( "set names utf8" );
//查询省份数据
$sql = "select * from `province`";
$result = mysql_query ( $sql );
if ($result && mysql_num_rows ( $result ) > 0) {
        //如果数据不为空,则逐条解析并加入下拉列表
        while ( $arr = mysql_fetch_array ( $result ) ) {
                echo "<option value='" . $arr ["id"] . "'>" . $arr ["name"] . "</option>";
        }
}
mysql_close ( $connect );
?>
</select> <select id="city">
                        <option value="">---市---</option>
                </select>
                <button id="commit">查询</button>
                <hr />
                <div id="weather"></div>
        </center>
</body>
</html>

city.php(获取城市信息页)

 

<?php
//设置返回的格式
header ( "Content-Type:text/html;charset=utf-8" );
//设置禁用缓存
header ( "Cache-Control:no-cache" );

//接收省份数据
$province_id = $_POST ['province'];

//打开数据库
$connect = mysql_connect ( "localhost", "root", "" );
mysql_select_db ( "weather_forecast" );
mysql_query ( "set names utf8" );
//查询数据
$sql = "select `name`, `city_number` from `city` where `province_id` = '" . $province_id . "'";
$result = mysql_query ( $sql );
$info = "";
if (mysql_num_rows ( $result ) > 0) {
        $info = "[";
        while ( $array = mysql_fetch_array ( $result ) ) {
                $info = $info.'{"name":"'.$array["name"].'","city_number":"'.$array["city_number"].'"},';
        }
        $info = substr($info, 0, strlen($info)-1);
        $info .= "]";
}
echo $info;
?>

 

forecast.php(请求跨域地址访问页)

 

<?php
//接受城市代码
$city_number = $_POST['city_number'];

//初始化
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "http://m.weather.com.cn/data/".$city_number.".html");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
// 3. 执行并获取HTML文档内容
$output = curl_exec($ch);
// 4. 释放curl句柄
curl_close($ch);

echo $output;
?>

 

weather_forecast.jsajax请求脚本)

 

$(function() {
        $("#province").change(
                        function() {
                                $.ajax({
                                        url : "/ajax/weather_forecast/city.php",
                                        type : "POST",
                                        data : {
                                                province : $("#province option:selected").val()
                                        },
                                        dataType : "json",
                                        success : function(data) {
                                                if (data == null || data == "") {
                                                        $("#city").empty();
                                                        $myoption = $("<option value=''>---市---</option>");
                                                        $("#city").append($myoption);
                                                        return;
                                                }
                                                $("#city").empty();
                                                for ( var i = 0; i < data.length; i++) {
                                                        $myoption = $("<option value='"
                                                                        + data[i].city_number + "'>" + data[i].name
                                                                        + "</option>");
                                                        $("#city").append($myoption);
                                                }
                                        }
                                });
                        });

        $("button").click(
                        function() {
                                if ($("#city").val() == null || $("#city").val() == "") {
                                        window.alert("请选择正确省份和城市");
                                        return;
                                }
                                 $.ajax({
                                 url: "/ajax/weather_forecast/forecast.php",
                                 type: "POST",
                                 data: {city_number:$("#city").val()},
                                 dataType: "json",
                                 success: function (data){
                                         var info = data.weatherinfo;
                                         var $table = "<table class='weather' border='1'><tr><th></th><th>今天</th><th>明天</th><th>后天</th></tr>";
                                         $table += "<tr><th>温度</th><td>"+info.temp1+"</td><td>"+info.temp2+"</td><td>"+info.temp3+"</td></tr>";
                                         $table += "<tr><th>天气</th><td>"+info.weather1+"</td><td>"+info.weather2+"</td><td>"+info.weather3+"</td></tr>";
                                         $table += "<tr><th>风速</th><td>"+info.wind1+"</td><td>"+info.wind2+"</td><td>"+info.wind3+"</td></tr>";
                                         $table += "<tr><th>风速级别</th><td>"+info.fl1+"</td><td>"+info.fl2+"</td><td>"+info.fl3+"</td></tr>";
                                         $table += "</table><br />";
                                         $table += "<table class='index' border='1'><tr><th colspan='3'>详细情况</th></tr>";
                                         $table += "<tr><th width='20%'>今天穿衣指数</th><td width='10%'>"+info.index+"</td><td width='70%'>"+info.index_d+"</td></tr>";
                                         $table += "<tr><th>48小时穿衣指数</th><td>"+info.index48+"</td><td>"+info.index48_d+"</td></tr>";
                                         $table += "<tr><th>紫外线及48小时紫外线</th><td>"+info.index_uv+"</td><td>"+info.index48_uv+"</td></tr>";
                                         $table += "<tr><th>洗车</th><td colspan='2'>"+info.index_xc+"</td></tr>";
                                         $table += "<tr><th>外出旅游</th><td colspan='2'>"+info.index_tr+"</td></tr>";
                                         $table += "<tr><th>舒适指数</th><td colspan='2'>"+info.index_co+"</td></tr>";
                                         $table += "<tr><th>晨练</th><td colspan='2'>"+info.index_cl+"</td></tr>";
                                         $table += "<tr><th>晾晒</th><td colspan='2'>"+info.index_ls+"</td></tr>";
                                         $table += "<tr><th>过敏</th><td colspan='2'>"+info.index_ag+"</td></tr>";
                                         $table += "</table>";
                                         $("#weather").html($table);
                                 }
                                 });
                        });
});

 

4、黄金价格实时监控
4.1需要两个页面,一个是展示页面,另一个是数据更新页面
4.2需要根据上次的数据和本次的数据算出涨跌并动态加载相应的图片资源
4.3设置两个计时器,一个负责发送ajax请求,另一个负责倒计时
4.4源代码
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>黄金价格走势</title>
<script type="text/javascript" src="../js/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="gold_price.js"></script>
</head>
<body>
        <div align="center">
                <h1>黄金价格走势</h1>
                <h3>每隔5秒刷新页面,距下次刷新还有<font id="sec">5</font></h3>
                <table align="center" width="300px">
                        <tr><td width="30%">市场</td><td width="30%">最新价格</td><td width="40%">涨跌</td></tr>
                        <tr id="ld"><td width="30%">伦敦</td><td width="30%">0</td><td width="40%">0</td></tr>
                        <tr id="tw"><td width="30%">台湾</td><td width="30%">0</td><td width="40%">0</td></tr>
                        <tr id="dj"><td width="30%">东京</td><td width="30%">0</td><td width="40%">0</td></tr>
                </table>
        </div>
</body>
</html>

gold_price.js

 

$(function (){
        run();
        //开启定时器
        var interval = null;
        var interval2 = null;
        function run() {
                if (interval == null) {
                        //设置定时器,每5秒钟执行getPrice函数一次
                        interval = setInterval(getPrice, "5000");
                }
                if (interval2 == null) {
                        interval2 = setInterval(jishi, "1000");
                }
        }
        //停止定时器 
        function stop() {
                if (interval != null)
                        clearTimeout(interval);
        }
        //发送ajax请求
        function getPrice() {
                $.ajax({
                        url: "/ajax/gold_price/price.php",
                        type: "POST",
                        data: {ld: $("#ld td:eq(1)").text(), tw: $("#tw td:eq(1)").text(), dj: $("#dj td:eq(1)").text()},
                        dataType: "json",
                        success: function(data) {
                                //伦敦
                                $("#ld > td:eq(1)").text(data.ld.price);
                                var $value = "0";
                                if (parseInt(data.ld.price_change) == 0) {
                                        $value = "0";
                                }else if (parseInt(data.ld.price_change) > 0) {
                                        $value = "<img src='up.png' alt='rise'>"+data.ld.price_change;
                                }else {
                                        $value = "<img src='down.png' alt='fall'>"+data.ld.price_change.substring(1);
                                }
                                $("#ld > td:eq(2)").html($value);
                                //台湾
                                $("#tw > td:eq(1)").text(data.tw.price);
                                var $value = "0";
                                if (parseInt(data.tw.price_change) == 0) {
                                        $value = "0";
                                }else if (parseInt(data.tw.price_change) > 0) {
                                        $value = "<img src='up.png' alt='rise'>"+data.tw.price_change;
                                }else {
                                        $value = "<img src='down.png' alt='fall'>"+data.tw.price_change.substring(1);
                                }
                                $("#tw > td:eq(2)").html($value);
                                //东京
                                $("#dj > td:eq(1)").text(data.dj.price);
                                var $value = "0";
                                if (parseInt(data.dj.price_change) == 0) {
                                        $value = "0";
                                }else if (parseInt(data.dj.price_change) > 0) {
                                        $value = "<img src='up.png' alt='rise'>"+data.dj.price_change;
                                }else {
                                        $value = "<img src='down.png' alt='fall'>"+data.dj.price_change.substring(1);
                                }
                                $("#dj > td:eq(2)").html($value);
                        }
                });
        }
        
        function jishi() {
                var t = parseInt($("#sec").text());
                if (t > 1) {
                        $("#sec").text(--t);
                }else {
                        $("#sec").text("0");
                        $("#sec").text("5");
                }
        }
});

 

price.php

 

<?php
//设置返回的格式
header ( "Content-Type:text/html;charset=utf-8" );
//设置禁用缓存
header ( "Cache-Control:no-cache" );
//接收数据
$ld_old = $_POST['ld'];
$tw_old = $_POST['tw'];
$dj_old = $_POST['dj'];
//生成三个动态数据
$ld = rand(500, 1500);
$tw = rand(500, 1500);
$dj = rand(500, 1500);
//计算涨跌,发送结果
$info = '{"ld":{"price":"'.$ld.'","price_change":"'.($ld-$ld_old).'"},';
$info .= '"tw":{"price":"'.$tw.'","price_change":"'.($tw-$tw_old).'"},';
$info .= '"dj":{"price":"'.$dj.'","price_change":"'.($dj-$dj_old).'"}}';
//写会数据
echo $info;

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2014-03-11 22:36  瑞诚  阅读(516)  评论(0编辑  收藏  举报