zoukankan      html  css  js  c++  java
  • XMLHttpRequest 学习(二)——封装一个ajax

    1、发起一个HTTP的步骤:

    1.    创建一个 XMLHttpRquest 实例,    
    1 var xhr=new XMLHttpRequest();

      2.初始化请求,

    1 xhr.open(method,URL,async);

      3.设置请求头信息,按需设置,不需要设置就到下一步,用 POST 方法时,必须将请求头设置为:

    1 xhr.setRequestHeader("Content-Type","appivation/x-www=form-unurlencoded");//在POST和PUT请求需要设置该信息

      4.绑定相关事件,异步请求中,readystatechange 必须班绑定,其他事件按需绑定

     1         //第四步 设置回调函数和xhr事件,在异步请求中必须绑定onreadystatechage事件,readyState改变就触发
     2         xhr.onreadystatechange=callback;//绑定一个函数
     3         //或者用匿名函数
     4         xhr.onreadystatechange=function (){
     5             if(xhr.readyState ==4 ){
     6                 if((xhr.status>=200&&xhr.status<300)||xhr.status==304){
     7                     //响应信息返回后处理,在页面提示用户
     8                 }
     9                 else{//返回消息失败
    10                     alert("响应失败!");
    11                 }
    12             }
    13             else{//请求未发送的处理
    14                 alert("请求未完成!")
    15             }
    16         }
    17         //send()调用后开始触发
    18         xhr.onloadstart=loadState;
    19         
    20         //文件上传可能需要设置这些事件
    21         //上传文件开始
    22         xhr.upload.onloadstart=uploadStart;
    23         //显示上传进度
    24         xhr.upload.onprogress=uploadProgress;
    25         //上传完成,成功
    26             //出现异常或者用户取消,激发abort、timeout、error事件,触发loadend事件
    27             xhr.onabort=abort;
    28             xhr.ontimeout=timeeout;
    29             xhr.onerror=error;
    30         xhr.upload.onload=upload;
    31         //上传结束,可能不成功
    32         xhr.upload.onloadend=uploadEnd;
    33         
    34         //显示下载进度
    35         xhr.onprogress=loadProgress;
    36         //出现异常或者用户取消,激发abort、timeout、error事件,触发loadend事件
    37         xhr.onabort=abort;
    38         xhr.ontimeout=timeeout;
    39         xhr.onerror=error;
    40         //下载完成,可能不成功
    41         xhr.onloadend=loadEnd;

       5.发送,在POST需要传递参数,最后将参数转码。

    //第五步 发送请求,在POST请求中需要给send传递参数
            xh.send();

     下面就根据上面的步骤,建立一个get请求:

    HTML:

     1 <div>
     2         <form >
     3             <fieldset>
     4                 <legend> xhr提交表单 </legend>
     5                 <lable>姓名:</lable>
     6                 <input type="text" id="name" name="name" value="周其军" placeholder="请输入您的姓名" />
     7                 <br>
     8                 <lable>邮箱:</lable>
     9                 <input type="email" placeholder="请输入邮箱" id="email" name="email" />
    10                 <br/>
    11                 <input type="button" id="button" value="提交" /> </fieldset>
    12         </form>
    13     </div>
    14     <div id="userInfor">
    15              <!--在这显示返回的内容-->
    16     </div>

    JS:

     1 window.onload=function(){ 
     2 var button=document.getElementById("button"); //获取button
     3     var userInfor=document.getElementById("userInfor");
     4     button.addEventListener("click",function(){
     5         var url="demo.php";
     6         var name=document.getElementById("name").value;
     7         var email=document.getElementById("email").value;
     8         //alert(name+email);
     9         url+="?name="+name+"&email="+email;
    10         var xhr=new XMLHttpRequest();
    11         /*xhr.setRequestHeader("jack","hahah");*/
    12         xhr.open("GET",url,true);//初始化一个异步请求
    13         xhr.onreadystatechange=function(){
    14             if(xhr.readyState==4){
    15                 if(xhr.status==200){
    16                     //将用户填写的信息显示出来
    17                     alert(xhr.response);
    18                 }
    19                 /*else{
    20                     alert("响应不成")
    21                 }*/
    22             }
    23             /*else{
    24                 alert("请求未发送!");
    25             }*/
    26         }
    27         xhr.send();
    28     });

    PHP:

    1 <?php
    2  header("Content-type: text/html; charset=utf-8"); 
    3 echo "<h2>名字:{$_REQUEST['name']}</h2>
    4        <span>邮箱:{$_REQUEST['email']}</span>";    
    5 
    6 ?>

    请求成功了,但是我想返回 html 片段,然后追加到 id=userInfor  的 div 里面,不知道怎么弄。也没搜索的可靠的做法。也是是我的 PHP 不对??

    2、封装一个 ajax 

     1         var ajax = {}; //封装一个ajax
     2         ajax.x = function () { //定义x,用于创建xhr。
     3             if (typeof XMLHttpRequest !== 'undefined') {
     4                 return new XMLHttpRequest();
     5             }
     6             var versions = [
     7         "MSXML2.XmlHttp.6.0"
     8         , "MSXML2.XmlHttp.5.0"
     9         , "MSXML2.XmlHttp.4.0"
    10         , "MSXML2.XmlHttp.3.0"
    11         , "MSXML2.XmlHttp.2.0"
    12         , "Microsoft.XmlHttp"
    13     ];
    14             var xhr;
    15             for (var i = 0; i < versions.length; i++) {
    16                 try {
    17                     xhr = new ActiveXObject(versions[i]);
    18                     break;
    19                 }
    20                 catch (e) {}
    21             }
    22             return xhr;
    23         };
    24         //定义 send()
    25         ajax.send = function (url, callback, method, data, async) {
    26             if (async === undefined) {
    27                 async = true;
    28             }
    29             var x = ajax.x();
    30             x.open(method, url, async);
    31             x.onreadystatechange = function () {
    32                 if (x.readyState == 4) {
    33                     callback(x.responseText)
    34                 }
    35             };
    36             if (method == 'POST') {
    37                 x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    38             }
    39             x.send(data)
    40         };
    41         //定义 get 请求
    42         ajax.get = function (url, data, callback, async) {
    43             var query = [];
    44             for (var key in data) {
    45                 query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
    46             }
    47             ajax.send(url + (query.length ? '?' + query.join('&') : ''), callback, 'GET', null, async)
    48         };
    49         //定义 post 请求
    50         ajax.post = function (url, data, callback, async) {
    51             var query = [];
    52             for (var key in data) {
    53                 query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
    54             }
    55             ajax.send(url, callback, 'POST', query.join('&'), async)
    56         };

    调用 ajax 的 方法:

     1 var button = document.getElementById("button");
     2         button.addEventListener("click", function () {
     3             var name = document.getElementById("name").value;
     4             var email = document.getElementById("email").value;
     5             var userInfor = document.getElementById("userInfor");
     6             ajax.get("demo1.php?rand=" + Math.random(), {
     7                 name: name
     8                 , email: email
     9             }, function () {
    10                 var xhr = ajax.x();
    11                 //alert("aa");
    12                 //alert(xhr.responseText);请求响应了,却没弹出 响应信息
    13                 userInfor.append(xhr.responseText);
    14             });
    15         });

    博客园插入代码还是很不方便,光标进入代码块后,不能移出来。

  • 相关阅读:
    Fastify 系列教程四 (求对象、响应对象和插件)
    Fastify 系列教程三 (验证、序列化和生命周期)
    Fastify 系列教程二 (中间件、钩子函数和装饰器)
    Fastify 系列教程一 (路由和日志)
    使用 Vuejs 开发 chrome 插件的注意事项
    五十行javascript代码实现简单的双向数据绑定
    markown编辑器截图粘贴预览,并将图片传至七牛云
    线程与进程的区别
    TeamViewer卡在正在初始化显示参数
    Chrome 字体模糊解决
  • 原文地址:https://www.cnblogs.com/jackzhoumine/p/6567226.html
Copyright © 2011-2022 走看看