Ajax原理和封装

来源:互联网 发布:淘宝修改手机绑定 编辑:程序博客网 时间:2024/06/05 02:06


Ajax原理和封装

一、    准备工作:服务器环境的搭建

服务器工具:

   http://www.php100.com/html/plugin/ser/2013/0905/91.html

   

把我们做的文件放到指定目录下

 

 

二、    Ajax原理

1   基本原理

a)  什么是Ajax

                   i.     Asynchronous JavaScript and XML(异步JavaScript和XML)

1.  节省用户操作,时间,提高用户体验,减少数据请求

2.  传输获取数据

b)  使用Ajax

                   i.     使用ajax获取某一文本文件的内容

 

用javascript异步形式去操作xml

数据交互

 

2   第一个程序实例

 

<script>

window.onload = function() {

  

   var oBtn = document.getElementById('btn');

  

  

   oBtn.onclick = function() {

      

       //打开浏览器

       var xhr = new XMLHttpRequest();

       //在地址栏输入地址

       xhr.open('get','1.txt',true);

       //提交

       xhr.send();

      

       //等待服务器返回内容

       xhr.onreadystatechange = function() {

         

          if ( xhr.readyState == 4 ) {

              alert( xhr.responseText );

          }

         

       }

      

   }

}

</script>

</head>

 

<body>

   <input type="button" value="按钮" id="btn" />

</body>

 

txt文件

hello

 

结果:显示hello

 

 

3   对象的创建和兼容处理

 

•    创建对象XMLHttpRequest()

–      Date()对象

–      ActiveXObject(‘Microsoft.XMLHTTP’)

 

 

//打开浏览器

       /*

          1.创建一个ajax对象

              ie6以下newActiveXObject('Microsoft.XMLHTTP')

       */

       var xhr = null;

       /*if (window.XMLHttpRequest) {

          xhr = new XMLHttpRequest();

       } else {

           xhr = newActiveXObject('Microsoft.XMLHTTP');

       }*/

       try {

          xhr = new XMLHttpRequest();

       } catch (e) {

          xhr = new ActiveXObject('Microsoft.XMLHTTP');

       }

 

 

异常处理:不会阻止后面程序的执行

 

<script>

 

//alert(a);

 

try {

   //代码尝试执行这个块中的内容,如果有错误,则会执行catch{}, 并且传入错误信息参数

   //alert(a);

   //new throw();

   //throw new Error('错了错了');//手动写错误

} catch (e) {

   alert(e);

}

 

alert('到这里了');

</script>

 

4   Open方法和表单

 

l  表单

•     什么是表单

–    向服务器提交数据,比如:提交用户信息

•     action    提交到哪里

•     method 提交方式

l  Get和Post的区别

•     传输方式的区别

–    Get通过url地址传输

–    Post通过浏览器内部传输

•     传输数据量

–    Get有数据量限制,每个浏览器都不同

–    Post理论上无限

 

l   后端数据的接收

n    $_GET

u - 通过URL传递给该脚本的变量的数组

n    $_POST

u - 通过HTTP POST方法(表单)传递给该脚本的变量的数组

n    前后台键名和传输方式必须一致

n    数据传输方式

n    数据获取方式

 

 

Get方式

<body>

  表单:数据的提交

      action : 数据提交的地址,默认是当前页面

        method : 数据提交的方式,默认是get方式

        1.get

            把数据名称和数据值用=连接,如果有多个的话,那么他会把多个数据组合用&进行连接,然后把数据放到url?后面传到指定页面

            2.post

        enctype : 提交的数据格式,默认application/x-www-form-urlencoded

    <formaction="1.get.php"enctype="application/x-www-form-urlencoded">

      <input type="text"name="username" />

        <inputtype="text" name="age" />

        <inputtype="submit" value="提交" />

    </form>

</body>

1.get.php文件

<?php

header('content-type:text/html;charset="utf-8"');

error_reporting(0);

 

$username = $_GET['username'];

$age = $_GET['age'];

 

echo "你的名字:{$username},年龄:{$age}";

 

 

post方式

<body>

表单:数据的提交

    action : 数据提交的地址,默认是当前页面

        method : 数据提交的方式,默认是get方式

            1.get

               把数据名称和数据值用=连接,如果有多个的话,那么他会把多个数据组合用&进行连接,然后把数据放到url?后面传到指定页面

                url长度限制的原因,我们不要通过get方式传递过多的数据

            2.post

               理论上无限制

        enctype : 提交的数据格式,默认application/x-www-form-urlencoded

    <formaction="1.post.php" method="post">

    <input type="text"name="username" />

        <inputtype="text" name="age" />

        <inputtype="submit" value="提交" />

    </form>

</body>

 

1.post.php

 

<?php

header('content-type:text/html;charset="utf-8"');

error_reporting(0);

 

$username = $_POST['username'];

$age = $_POST['age'];

 

echo "你的名字:{$username},年龄:{$age}";

 

l    Open方法

•    三个参数的含义

–      1、提交方式Form-method

–      2、提交地址Form-action

–      3、异步(同步)

 

l    Send方法

•    发送数据请求,相当于Form的submit

 

 

 

 

//在地址栏输入地址

       /*

          open方法

          参数

              1.打开方式

              2.地址

              3.是否异步

                 异步:非阻塞前面的代码不会影响后面代码的执行

                 同步:阻塞前面的代码会影响后面代码的执行

       */

       xhr.open('get','1.txt',true);

 

   //提交 发送请求

       //alert(1);

       xhr.send();

 

5   数据的获取

 

l   请求状态监控

onreadystatechange事件

•    readyState属性:请求状态

–      0   (初始化)还没有调用open()方法

–      1   (载入)已调用send()方法,正在发送请求

–      2   (载入完成)send()方法完成,已收到全部响应内容

–      3   (解析)正在解析响应内容

–      4   (完成)响应内容解析完成,可以在客户端调用了

•    status属性:服务器(请求资源)的状态

•    返回的内容

–      responseText:返回以文本形式存放的内容

–      responseXML:返回XML形式的内容

 

   //等待服务器返回内容

       /*

          readyState : ajax工作状态

          responseText : ajax请求返回的内容就被存放到这个属性下面

          on readystate change : 当readyState改变的时候触发

          status : 服务器状态,http状态码

       */

       xhr.onreadystatechange = function() {

         

          if ( xhr.readyState == 4 ) {

              if ( xhr.status == 200 ) {

                 alert( xhr.responseText );

              } else {

                 alert('出错了,Err:' + xhr.status);

              }

          }

         

       }

 

6   应用中get和post的区别处理

a) 发送请求(get和post的区别)

                         i.     send(要发送的数据):发送请求

1. 中文编码

2. 缓存

3. POST:setRequestHeader(类型, 内容):设置请求头

4. "Content-Type","application/x-www-form-urlencoded”

 

 

Get方式

<title>无标题文档</title>

<!--<scriptsrc="jquery.js"></script>-->

<script>

//$(function(){})    //阻塞 -> 同步

 

//非阻塞 - 异步

/*setTimeout(function() {

   alert(1);

}, 2000);

 

alert(2);*/

 

window.onload = function() {

  

   var oBtn = document.getElementById('btn');

  

  

   oBtn.onclick = function() {

      

       var xhr = null;

       try {

          xhr = new XMLHttpRequest();

       } catch (e) {

          xhr = new ActiveXObject('Microsoft.XMLHTTP');

       }

       /*

          1.缓存 在url?后面连接一个随机数,时间戳

          2.乱码 编码encodeURI

       */

       xhr.open('get','2.get.php?username='+encodeURI('刘伟')+'&age=30&' + newDate().getTime(),true);

       xhr.send();

      

       xhr.onreadystatechange = function() {

         

          if ( xhr.readyState == 4 ) {

              if ( xhr.status == 200 ) {

                 alert( xhr.responseText );

              } else {

                 alert('出错了,Err:' + xhr.status);

              }

          }

         

       }

      

   }

}

</script>

</head>

 

<body>

   <input type="button" value="按钮" id="btn" />

</body>

 

 

Post方式

 

<title>无标题文档</title>

<!--<scriptsrc="jquery.js"></script>-->

<script>

//$(function(){})    //阻塞 -> 同步

 

//非阻塞 - 异步

/*setTimeout(function() {

   alert(1);

}, 2000);

 

alert(2);*/

 

window.onload = function() {

  

   var oBtn = document.getElementById('btn');

  

  

   oBtn.onclick = function() {

      

       var xhr = null;

       try {

          xhr = new XMLHttpRequest();

       } catch (e) {

          xhr = new ActiveXObject('Microsoft.XMLHTTP');

       }

      

       xhr.open('post','2.post.php',true);

       //post方式,数据放在send()里面作为参数传递

       xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');//申明发送的数据类型

       //post没有缓存问题

       //无需编码

       xhr.send('username=刘伟&age=30');

      

       xhr.onreadystatechange = function() {

         

          if ( xhr.readyState == 4 ) {

              if ( xhr.status == 200 ) {

                 alert( xhr.responseText );

              } else {

                 alert('出错了,Err:' + xhr.status);

              }

          }

         

       }

      

   }

}

</script>

</head>

 

<body>

   <input type="button" value="按钮" id="btn" />

</body>

 

7   Ajax获取数据的处理

a) 数据类型(返回数据的处理)

                         i.     服务器返回给咱们的真正数据

                       ii.     XML、HTML、JSON

1. JSON的写法

2. Eval解析JSON的时候需要注意的地方

3. JSON.parse() :字符串解析成对象

 

<script>

/*

JSON :

*/

 

//alert(JSON)

 

//stringify : 可以把一个对象转成对应字符串

 

var arr = [1,2,3];

var j = {left:100};

alert( JSON.stringify(arr));//字符串格式[1,2,3]

alert( JSON.stringify(j));//{"left":100}自动转为规范模式

 

//parse : 可以把字符串转成对应对象

var s1 = '[100,200,300]';

var a1 = JSON.parse(s1);

alert(a1[0])//100

 

var s2 ='{"left":100}';

 var a2 = JSON.parse(s2);//100 s2格式要求严格 名字必须是双引号

alert(a2.left)

</script>

</head>

 

 

 

 

8   Ajax实例1:数据格式转换

<!DOCTYPE HTML>

<html>

<head>

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

<title>无标题文档</title>

<!--<scriptsrc="jquery.js"></script>-->

<script>

//$(function(){})    //阻塞 -> 同步

 

//非阻塞 - 异步

/*setTimeout(function() {

   alert(1);

}, 2000);

 

alert(2);*/

 

window.onload = function() {

  

   var oBtn = document.getElementById('btn');

  

  

   oBtn.onclick = function() {

      

       var xhr = null;

       try {

          xhr = new XMLHttpRequest();

       } catch (e) {

          xhr = new ActiveXObject('Microsoft.XMLHTTP');

       }

      

       xhr.open('get','getList.php',true);

       xhr.send();

      

       xhr.onreadystatechange = function() {

         

          if ( xhr.readyState == 4 ) {

              if ( xhr.status == 200 ) {

                 //alert( xhr.responseText );

              } else {

                 alert('出错了,Err:' + xhr.status);

              }

          }

         

       }

      

   }

}

</script>

</head>

 

<body>

   <input type="button" value="按钮" id="btn" />

</body>

</html>

 

getList.php文件

<?php

header('content-type:text/html;charset="utf-8"');

error_reporting(0);

 

$arr1 =array('leo','momo','zhangsen');

 

/*$arr2 =array('username'=>'leo','age'=>32);*/

 

echojson_encode($arr1);

9   Ajax实例2:定时刷新数据(ajax封装方式)

 

<script src="ajax.js"></script>

<script>

window.onload = function() {

  

   var oBtn = document.getElementById('btn');

  

  

   oBtn.onclick = function() {

      

       /*ajax({

          url :   'getNews.php',

          success : function(data) {

              //...

          }

       });*/

      

       ajax('get','getNews.php','',function(data) {

          var data = JSON.parse( data );

             

          var oUl = document.getElementById('ul1');

          var html = '';

          for (var i=0; i<data.length; i++) {

              html += '<li><a href="">'+data[i].title+'</a>[<span>'+data[i].date+'</span>]</li>';

          }

          oUl.innerHTML = html;

       });

      

       setInterval(function() {

          ajax('get','getNews.php','',function(data) {

              var data = JSON.parse( data );

                

              var oUl = document.getElementById('ul1');

              var html = '';

              for (var i=0; i<data.length; i++) {

                 html += '<li><ahref="">'+data[i].title+'</a>[<span>'+data[i].date+'</span>]</li>';

              }

              oUl.innerHTML = html;

          });

       }, 1000);

      

   }

}

</script>

</head>

 

<body>

   <input type="button" value="按钮" id="btn" />

    <ul id="ul1"></ul>

</body>

 

Ajax.js文件

 

functionajax(method, url, data, success) {

   var xhr = null;

   try {

       xhr = new XMLHttpRequest();

   } catch (e) {

       xhr = newActiveXObject('Microsoft.XMLHTTP');

   }

  

   if (method == 'get' && data) {

       url += '?' + data;

   }

  

   xhr.open(method,url,true);

   if (method == 'get') {

       xhr.send();

   } else {

       xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');

       xhr.send(data);

   }

  

   xhr.onreadystatechange = function() {

      

       if ( xhr.readyState == 4 ) {

          if ( xhr.status == 200 ) {

              success &&success(xhr.responseText);

          } else {

              alert('出错了,Err:'+ xhr.status);

          }

       }

      

   }

}

GetNews.php文件

 

<?php

header('content-type:text/html;charset="utf-8"');

error_reporting(0);

 

$news = array(

   array('title'=>'德国女总理默克尔滑雪时摔倒骨盆断裂','date'=>'2014-1-6'),

   array('title'=>'中日驻英外交官撰文互称对方国家为"伏地魔"','date'=>'2014-1-6'),

   array('title'=>'安倍:望与中国领导人会面 中方:你关闭了大门','date'=>'2014-1-6'),

   array('title'=>'揭秘台湾驻港间谍网运作湖北宜昌副市长被查','date'=>'2014-1-6'),

   array('title'=>'习近平:嫦娥三号是货真价实的中国创造','date'=>'2014-1-6'),

   array('title'=>'习近平:嫦娥三号是货真价实的中国创造','date'=>'2014-1-6'),

   array('title'=>'习近平:嫦娥三号是货真价实的中国创造','date'=>'2014-1-6'),

   array('title'=>'习近平:嫦娥三号是货真价实的中国创造','date'=>'2014-1-6'),

   array('title'=>'习近平:嫦娥三号是货真价实的中国创造','date'=>'2014-1-6'),

   array('title'=>'中国长达13年游戏机禁令正式解除 外企可进入','date'=>'2014-1-6'),

   array('title'=>'70种证件伴中国人一生:领养老金要办生存证明','date'=>'2014-1-6'),

   array('title'=>'德国女总理默克尔滑雪时摔倒骨盆断裂','date'=>'2014-1-6'),

   array('title'=>'中日驻英外交官撰文互称对方国家为"伏地魔"','date'=>'2014-1-6'),

   array('title'=>'安倍:望与中国领导人会面 中方:你关闭了大门','date'=>'2014-1-6'),

   array('title'=>'揭秘台湾驻港间谍网运作湖北宜昌副市长被查','date'=>'2014-1-6'),

);

 

echojson_encode($news);

10   

 

 


0 0