AJax学习笔记

ajax是什么?

①      ajax(asynchronouse javascript and xml) 异步的javascript 和 xml

②      是7种技术的综合,它包含了七个技术( javascript xml xstlxhtml dom xmlhttprequest, css),  ajax  是一个粘合剂,

③      ajax是一个与服务端语言无关的技术.即可以使用在(php/java ee/.net网站/ asp)

④      ajax可以给客户端返回三种格式数据(文本格式 ,xml , json格式)

⑤      无刷新数据交换技术有以下: flash, java applet, 框架,iframe,  ajax)

 

 

ajax 的运行原理分析


 

看一个需求:

 

 

 ajax在什么地方用的多

 

1 动态加载数据,按需取得数据。【树形菜单、联动菜单.../省市联动】

2 改善用户体验。【输入内容前提示、带进度条文件上传...】

 

3 电子商务应用。 【购物车、邮件订阅...】

4 访问第三方服务。    【访问搜索服务、rss阅读器】

5. 数据的布局刷新

 

经典的案例

 

 

使用ajax与服务器通信的的步骤

①     创建一个XMLHttpRequest对象

②     创建url,data,通过 xmlHttpRequest.send()

③     服务器端接收 ajax的请求,做相应处理(操作数据库),然后返回结果(echo 语句)

④     客户端通过xmlHttpRequest的属性 reponseText , responseXML 取的数据,然后就完成局部刷新当前页面任务

 

1.     使用 ajax完成用户名的验证

 

register.php

 

<html>

<head>

<title>用户注册</title>

<metahttp-equiv="content-type"content="text/html;charset=utf-8"/>

<scripttype="text/javascript">

 

       //创建ajax引擎

       function getXmlHttpObject(){

             

              var xmlHttpRequest;

              //不同的浏览器获取对象xmlhttprequest 对象方法不一样

              if(window.ActiveXObject){

                    

                     xmlHttpRequest=newActiveXObject("Microsoft.XMLHTTP");

                    

              }else{

 

                     xmlHttpRequest=newXMLHttpRequest();

              }

 

              return xmlHttpRequest;

 

       }

       var myXmlHttpRequest="";

 

       //验证用户名是否存在

       function checkName(){

             

              myXmlHttpRequest=getXmlHttpObject();

 

              //怎么判断创建ok

              if(myXmlHttpRequest){

                    

                     //通过myXmlHttpRequest对象发送请求到服务器的某个页面

                     //第一个参数表示请求的方式, "get" / "post"

                     //第二个参数指定url,对哪个页面发出ajax请求(本质仍然是http请求)

                     //第三个参数表示 true表示使用异步机制,如果false表示不使用异步

                     varurl="/ajax/registerProcess.php?mytime="+new Date()+"&username="+$("username").value;

                     //打开请求.

                     myXmlHttpRequest.open("get",url,true);

                     //指定回调函数.chuli是函数名

                     myXmlHttpRequest.onreadystatechange=chuli;

 

                     //真的发送请求,如果是get请求则填入 null即可

                     //如果是post请求,则填入实际的数据

                     myXmlHttpRequest.send(null);

 

 

              }

       }

 

       //回调函数

       function chuli(){

             

              //window.alert("处理函数被调回"+myXmlHttpRequest.readyState);

              //我要取出从registerPro.php页面返回的数据

              if(myXmlHttpRequest.readyState==4){

                    

                     //取出值,根据返回信息的格式定.text

                     //window.alert("服务器返回"+myXmlHttpRequest.responseText);

 

                     $('myres').value=myXmlHttpRequest.responseText;

              }

       }

 

       //这里我们写一个函数

       function $(id){

              returndocument.getElementById(id);

       }

</script>

</head>

<body>

       <form action="???"method="post">

    用户名字:<inputtype="text" οnkeyup="checkName();" name="username1" id="username"><inputtype="button" οnclick="checkName();"  value="验证用户名">

    <input style="border-width:0;color: red" type="text" id="myres">

    <br/>

    用户密码:<inputtype="password" name="password"><br>

    电子邮件:<inputtype="text" name="email"><br/>

    <input type="submit"value="用户注册">

    </form>

     <form action="???"method="post">

    用户名字:<inputtype="text" name="username2" >

  

    <br/>

    用户密码:<inputtype="password" name="password"><br>

    电子邮件:<inputtype="text" name="email"><br/>

    <input type="submit"value="用户注册">

    </form>

 

</body>

</html>

 

 

registerpro.php

 

<?php

      

       //这里两句话很重要,第一讲话告诉浏览器返回的数据是xml格式

       header("Content-Type:text/xml;charset=utf-8");

       //告诉浏览器不要缓存数据

       header("Cache-Control:no-cache");

 

       //接收数据

       $username=$_GET['username'];

 

 

       if($username=="shunping"){

              echo "用户名不可以用";//注意,这里数据是返回给请求的页面.

       }else{

              echo "用户名可以用";

       }

 

      

      

 

?>  

 

 

 

 

 

 

 

 

 ajax的post方式请求

 

在前面案例我们修改一下 :

 

 

关键代码

register.php

var url="/ajax/registerProcess.php";

                     //这个是要发送的数据

                     vardata="username="+$('username').value;

                     //打开请求.

                     myXmlHttpRequest.open("post",url,true);

                     //还有一句话,这句话必须.

                     myXmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

                     //指定回调函数.chuli是函数名

                     myXmlHttpRequest.onreadystatechange=chuli;

 

                     //真的发送请求,如果是get请求则填入 null即可

                     //如果是post请求,则填入实际的数据

                     myXmlHttpRequest.send(data);

registerPro.php关键码 :

$username=$_POST['username'];

 

 

☞ 使用get方式发出请求,如果提交的用户名不变化,浏览器将不会真的发请求,而是缓存取数据., url

 

解决方法

1.      url 后带一个总是变化的参数,比如当前时间

varurl="/ajax/registerProcess.php?mytime="+new Date()+"&username="+$("username").value;

2.      在服务器回送结果时,禁用缓存.

 

//这里两句话很重要,第一讲话告诉浏览器返回的数据是xml格式

       header("Content-Type:text/xml;charset=utf-8");

       //告诉浏览器不要缓存数据

       header("Cache-Control:no-cache");

 

 

 

 ajax如何处理返回的数据格式是xml的情况

 

register.php

 

<html>

<head>

<title>用户注册</title>

<metahttp-equiv="content-type" content="text/html;charset=utf-8"/>

<scripttype="text/javascript">

 

       //创建ajax引擎

       function getXmlHttpObject(){

             

              var xmlHttpRequest;

              //不同的浏览器获取对象xmlhttprequest对象方法不一样

              if(window.ActiveXObject){

                    

                     xmlHttpRequest=newActiveXObject("Microsoft.XMLHTTP");

                    

              }else{

 

                     xmlHttpRequest=newXMLHttpRequest();

              }

 

              return xmlHttpRequest;

 

       }

       var myXmlHttpRequest="";

 

       //验证用户名是否存在

       function checkName(){

             

              myXmlHttpRequest=getXmlHttpObject();

 

              //怎么判断创建ok

              if(myXmlHttpRequest){

                    

                     //通过myXmlHttpRequest对象发送请求到服务器的某个页面

                     //第一个参数表示请求的方式, "get" / "post"

                     //第二个参数指定url,对哪个页面发出ajax请求(本质仍然是http请求)

                     //第三个参数表示 true表示使用异步机制,如果false表示不使用异步

                     varurl="/ajax/registerProcess.php";

                     //这个是要发送的数据

                     vardata="username="+$('username').value;

                     //打开请求.

                     myXmlHttpRequest.open("post",url,true);

                     //还有一句话,这句话必须.

                     myXmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

                     //指定回调函数.chuli是函数名

                     myXmlHttpRequest.onreadystatechange=chuli;

 

                     //真的发送请求,如果是get请求则填入 null即可

                     //如果是post请求,则填入实际的数据

                     myXmlHttpRequest.send(data);

 

 

              }

       }

 

       //回调函数

       function chuli(){

             

              //window.alert("处理函数被调回"+myXmlHttpRequest.readyState);

              //我要取出从registerPro.php页面返回的数据

              if(myXmlHttpRequest.readyState==4){

                    

                     //取出值,根据返回信息的格式定.text

                     //window.alert("服务器返回"+myXmlHttpRequest.responseText);

 

                     //$('myres').value=myXmlHttpRequest.responseText;

 

                     //看看如果取出 xml格式数据

                     //window.alert(myXmlHttpRequest.responseXML);

             

                     //获取mes节点

                     varmes=myXmlHttpRequest.responseXML.getElementsByTagName("mes");

 

                     //取出mes节点值

                     //window.alert(mes.length);

                     //mes[0]->表示取出第一个mes节点

                     //mes[0].childNodes[0]->表示第一个mes节点的第一个子节点

                     varmes_val=mes[0].childNodes[0].nodeValue;

 

                     $('myres').value=mes_val;

              }

       }

 

       //这里我们写一个函数

       function $(id){

              returndocument.getElementById(id);

       }

</script>

</head>

<body>

       <form action="???"method="post">

    用户名字:<inputtype="text"   name="username1" id="username"><inputtype="button" οnclick="checkName();"  value="验证用户名">

    <input style="border-width:0;color: red" type="text" id="myres">

    <br/>

    用户密码:<inputtype="password" name="password"><br>

    电子邮件:<inputtype="text" name="email"><br/>

    <input type="submit"value="用户注册">

    </form>

     <form action="???"method="post">

    用户名字:<inputtype="text" name="username2" >

  

    <br/>

    用户密码:<inputtype="password" name="password"><br>

    电子邮件:<inputtype="text" name="email"><br/>

    <input type="submit"value="用户注册">

    </form>

 

</body>

</html>

 

 

regisgerProcess.php

 

<?php

      

       //这里两句话很重要,第一讲话告诉浏览器返回的数据是xml格式

       header("Content-Type: text/xml;charset=utf-8");

       //告诉浏览器不要缓存数据

       header("Cache-Control:no-cache");

 

       //接收数据(这里要和请求方式对于 _POST 还是 _GET)

       $username=$_POST['username'];

 

       //这里我们看看如何处理格式是xml

       $info="";

       if($username=="shunping"){

             $info.="<res><mes>用户名不可以用,对不起</mes></res>";//注意,这里数据是返回给请求的页面.

       }else{

              $info.="<res><mes>用户名可以用,恭喜</mes></res>";

       }

 

       echo $info;

      

 

?>  

 

 ajax如何处理json数据格式

 

①      json的格式如下 :

 

"{属性名:属性值,属性名:属性值,.... }"

因为json数据是原生态数据,因此这种数据格式很稳定,而且描述能力强,我们建议大家使用json格式

 

②      json数据格式的扩展

 

如果服务器返回的json 是多组数据,则格式应当如下:

 

$info="[{"属性名":"属性值",...},{"属性名":"属性值",...},....]";

 

在xmlhttprequest对象接收到json数据后,应当这样处理

 

 

//转成对象数组

 

varreses=eval("("+xmlHttpRequest.responseText+")");

 

//通过reses可以取得你希望的任何一个值

 

reses[?].属性名

 

 

③      更加复杂的json数据格式

 

<scriptlanguage="JavaScript">

     var people ={

            "programmers":

              [

                {"firstName":"Brett", "email": "brett@newInstance.com" },

                {"firstName":"Jason", "email": "jason@servlets.com" }

              ],

            "writer":

                     [

                            {"writer":"宋江","age":"50"},

                            {"writer":"吴用","age":"30"}

                     ],

                     "sex":"男"

                      

};

 

 

window.alert(people.programmers[0].firstName);

window.alert(people.programmers[1].email);

 

window.alert(people.writer[1].writer);

window.alert(people.sex);

 </script>

 

 

u 小结:

当一个ajax请求到服务器,服务器可以根据需求返回 三种格式的数据,那么我们应当选择哪一个?

 

1.      如果你的项目经理没有特殊的要求,建议使用json

2.      若应用程序不需要与其他应用程序共享数据的时候, 使用 HTML 片段来返回数据时最简单的

3.      如果数据需要重用, JSON 文件是个不错的选择, 其在性能和文件大小方面有优势

4.      当远程应用程序未知时, XML 文档是首选, 因为 XML 是 web 服务领域的 “世界语”

 

 

 ajax的省市联动案例(如何动态的从服务器取得数据)

 

showCities.php页面

<html>

<head>

<metahttp-equiv="content-type"content="text/html;charset=utf-8"/>

<scripttype="text/javascript">

 

 

//创建ajax引擎

       function getXmlHttpObject(){

             

              var xmlHttpRequest;

              //不同的浏览器获取对象xmlhttprequest对象方法不一样

              if(window.ActiveXObject){

                    

                     xmlHttpRequest=newActiveXObject("Microsoft.XMLHTTP");

                    

              }else{

 

                     xmlHttpRequest=newXMLHttpRequest();

              }

 

              return xmlHttpRequest;

 

       }

 

       var myXmlHttpRequest="";

 

functiongetCities(){

 

       myXmlHttpRequest=getXmlHttpObject();

 

       if(myXmlHttpRequest){

             

              var url="/ajax/showCitiesPro.php";//post

              vardata="province="+$('sheng').value;

 

              myXmlHttpRequest.open("post",url,true);//异步方式

 

              myXmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

 

              //指定回调函数

              myXmlHttpRequest.onreadystatechange=chuli;

 

              //发送

              myXmlHttpRequest.send(data);

       }

}

 

       function chuli(){

              if(myXmlHttpRequest.readyState==4){

                    

                     if(myXmlHttpRequest.status==200){

                           

                            //取出服务器回送的数据

 

                            varcities=myXmlHttpRequest.responseXML.getElementsByTagName("city");

                           

                            $('city').length=0;

                            varmyOption=document.createElement("option");

                                  

                                   myOption.innerText="--城市--";

                                   //添加到

                                   $('city').appendChild(myOption);

 

                            //遍历并取出城市

                            for(vari=0;i<cities.length;i++){

                                  

                                   varcity_name=cities[i].childNodes[0].nodeValue;

                                   //创建新的元素option

                                   varmyOption=document.createElement("option");

                                   myOption.value=city_name;

                                   myOption.innerText=city_name;

                                   //添加到

                                   $('city').appendChild(myOption);

                            }

                     }

              }

       }

 

 

       //这里我们写一个函数

       function $(id){

              returndocument.getElementById(id);

       }

 

</script>

</head>

<body>

<selectid="sheng" οnchange="getCities();">

    <option value="">---省---</option>

    <option value="zhejiang">浙江</option>

    <option value="jiangsu" >江苏</option>

    <option value="sichuan" >四川</option>

    </select>

    <select id="city">

    <option value="">--城市--</option>

    </select>

   

     <select id="county">

    <option value="">--县城--</option>

    </select>

 

</body>

</html>

 

**showCitiesProcess.php**

 

<?php

 

       //服务器端

 

       //这里两句话很重要,第一讲话告诉浏览器返回的数据是xml格式

       header("Content-Type:text/xml;charset=utf-8");

       //告诉浏览器不要缓存数据

       header("Cache-Control:no-cache");

 

 

       //接收用户的选择的省的名字

 

       $province=$_POST['province'];

 

       file_put_contents("d:/mylog.log",$province."\r\n",FILE_APPEND);

       //如何在调试过程中,看到接收到的数据 。

       //到数据库去查询省有那些城市(现在先不到数据库)

       $info="";

       if($province=="zhejiang"){

             

              $info="<province><city>杭州</city><city>温州</city><city>宁波</city></province>";

       }else if($province=="jiangsu"){

              $info="<province><city>南京</city><city>徐州</city><city>苏州</city></province>";

       }

             

 

       echo $info;

 

?>

 

 

黄金价格波动图

 

glodPrice.php界面

<html>

       <head>

              <metahttp-equiv="content-type"content="text/html;charset=utf-8"/>

              <linkhref="Untitled-1.css" rel="stylesheet"type="text/css" />

              <script src="my.js"type="text/javascript"></script>

              <scripttype="text/javascript">

             

      

                     var myXmlHttpRequest;

 

                     function updateGoldPrice(){

                           

                           

                            myXmlHttpRequest=getXmlHttpObject();

 

                            if(myXmlHttpRequest){

                           

                                  

                                   //创建ajax引擎成功

                                   varurl="glodPriceProcess.php";

                                   vardata="city[]=dj&city[]=tw&city[]=ld";

 

                                   myXmlHttpRequest.open("post",url,true);

 

                                   myXmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

 

                                   myXmlHttpRequest.onreadystatechange=functionchuli(){

                                         

                                          //接收数据json

                                          if(myXmlHttpRequest.readyState==4){

                                                 if(myXmlHttpRequest.status==200){

                                                

                                                        //取出并转成对象数组

                                          varres_objects=eval("("+myXmlHttpRequest.responseText+")");

 

                                                        $('dj').innerText=res_objects[0].price;

                                                        $('tw').innerText=res_objects[1].price;

                                                        $('ld').innerText=res_objects[2].price;

 

                                                 }

                                          }    

 

                                   }

                                   myXmlHttpRequest.send(data);

 

 

                                  

 

                            }

 

                     }

 

                     //使用定时器 每隔5 秒

                     window.setInterval("updateGoldPrice()",5000);

             

                    

              </script>

       </head>

       <center>

              <h1>每隔5秒中更新数据(以1000为基数计算涨跌)</h1>

       <table border=0class="abc">

              <tr><tdcolspan="3"><img src="gjhj_bj_tit.gif"/></td></tr>

              <tr ><td>市场</td><td>最新价格$</td><td>涨跌</td></tr>

              <tr><td>伦敦</td><tdid="ld">788.7</td><td><img src="down.gif"/>211.3</td></tr>

              <tr><td>台湾</td><tdid="tw">854.0</td><td><img src="down.gif"/>146.0</td></tr>

              <tr><td>东京</td><tdid="dj">1791.3</td><td><img src="up.gif"/>791.3</td></tr>

       </table>

</center>

</html>

 

glodPriceProcess.php

 

<?php

 

      

       //这里两句话很重要,第一讲话告诉浏览器返回的数据是xml格式

       header("Content-Type:text/html;charset=utf-8");

       //告诉浏览器不要缓存数据

       header("Cache-Control:no-cache");

 

       //接收

 

       $cities=$_POST['city'];

 

       //随机的生成 三个 500-2000间数

       //$res='[{"price":"400"},{"price":"1000"},{"price":"1200"}]';

      

       $res='[';

 

 

       for($i=0;$i<count($cities);$i++){

             

              if($i==count($cities)-1){

                     $res.='{"cityname":"'.$cities[$i].'","price":"'.rand(500,1500).'"}]';

              }else{

                    

                     $res.='{"cityname":"'.$cities[$i].'","price":"'.rand(500,1500).'"},';

              }

 

       }

 

       file_put_contents("d:/mylog.log",$res."\r\n",FILE_APPEND);

 

       echo $res;

 

 

?>

 

晚上的练习

 

1.      把省市联动 和数据库

2.      把黄金价格波动的 上下箭头指示做出来

3.      把用户管理系统(信息共享系统),使用更加规范的mvc模式开发(引入smarty)

 

 

 

 

 

 

如果我们的代码比较复杂,可以通过

file_put_contents来输出信息到某个日志文件.(!!!!!!!)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值