jquery入门(五)——ajax的封装

1.AJAX(Asynchronous JavaScript And XML)

HTML 用于建立 Web 表单并确定应用程序其他部分使用的字段。
JavaScript 代码是运行 AJAX 应用程序的核心代码,帮助改进与服务器应用程序的通信。
DHTML 或 Dynamic HTML,用于动态更新表单。
文档对象模型 DOM 用于处理 HTML 结构和服务器返回的 XML。

2.AJAX执行流程

这里写图片描述

(1)获得XMLHttpRequest

    var xmlHttp;
     //获取xmlhttprequest异步请求的对象
        function getxmlHttpRequest()
        {
                if(window.ActiveObject)
                {
                xmlHttp = new ActiveOject("Microsoft.XMLHTTP");
                }else if(window.XMLHttpRequest){
                xmlHttp = new XMLHttpRequest();
                }

        }

(2)调用open方法建立与服务器的链接




open(method,url,async)

规定请求的类型、URL 以及是否异步处理请求。
method:请求的类型;GET 或 POST
url:文件在服务器上的位置
async:true(异步)或 false(同步)

例:

function fun()
    {
    getxmlHttpRequest();

    var name=document.getElementById("username").value;

    var pwd=document.getElementById("password").value;

    xmlHttp.open("get","Login?name="+name+"&pwd="+pwd,true);
    //(3)指定回调函数
    xmlHttp.onreadystatechange = myfun;
    //(4)向服务器发送请求
    xmlHttp.send(null);
    }

(3)指定回调函数

function myfun(){
        if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
        {
        var str = xmlHttp.responseText;
        var sp = document.getElementById("str");
        sp.innerHTML=str;
        }
        }

(4)向服务器发送请求

 xmlHttp.send(null);

html:

    用户名:<input type="text" id="username"><br>
       密码:<input type="password" id="password">
       <input type="button" value="登录" onclick="fun();">
       <span id="str"></span>

servlet:

     //1.设置编码格式
            request.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=utf-8");
            //2.获取客户端的请求参数
            String name = request.getParameter("name");
            String pwd = request.getParameter("pwd");
            String str=null;
            if("abc".equals(name)&&"111".equals(pwd))
            {
                str="合法用户";
            }
            else
            {
                str="非法用户";
            }

            response.getWriter().print(str);

当用户点击登录按钮时,会调用fun(),将输入框中的用户名及及密码获取,并传给后台,回调函数对返回的值进行判断,并将传回的值显示在名为str的span上从而通过异步刷新实现帐号密码验证,这里servlet仅为写死的值未与dao层交互。

3. jQuery对Ajax的封装.

jQuery对Ajax做了大量的封装,我们使用起来也比较方便,不需要去考虑浏览器兼容性。对于封装的方式,jQuery采用了三层封装:jQuery对Ajax做了大量的封装,我们使用起来也比较方便,不需要去考虑浏览器兼容性。对于封装的方式,jQuery采用了三层封装:
最底层的封装方法为:$.ajax();

第二层有三种方法:load()、 . g e t ( ) .post()

最高层: . g e t S c r i p t ( ) .getJSON()

(1)$.ajax()方法:

是所有ajax方法中最底层的方法,所有其他方法都是基于该方法的封装,这个方法只有一个参数,传递一个不同功能的键值对的对象;
参数键/值对:

   type:'数据提交方式'

   url:'服务器页面'

   data:'传递的参数'

   success:'回调函数,将信息显示在页面上'

例如:

    $("input").click(function(){
         $.ajax({
             type:'post',
             url:'006.jsp',
             data:{
                 name:'abc'
             },
             success:function(response,status,xhr){
                 $("#box").html(response);
             }
           });
         });

就可以将上面的例子优化为:

    $(function(){
        $("#btn1").click(function(){
        $.ajax({
        type:'get',
        url:'Login',
        data:{
            name:$("#username").val(),
            pwd:$("#password").val()
        },
        success:function(response,status,xhr){
            alert(html(response));
        }
        });
        });
        });

与之前的例子相比,jqueryy对ajax封装以后使用起来更加方便,快捷。

(2)load()方法有三个参数:

   url:必须的,请求html文件的url地址,为String类型

   data:可选,发送的key/value数据,Object类型

   callback:可选,回调函数,function类型

例如:

(1) 用Ajax异步载入一段html内容:

     //html:
        <input type="button" value="异步获取数据"/>
        <div id="box"></div>

        //jQuery

          $("input").click(function(){
             $("#box").load("test.html");
          });

(2)如果是服务器文件,比如.jsp。一般不仅需要载入数据,还需要向服务器提交数据,那么我们就可以使用第二个可选参数data.向服务器提交数据有两种方式:get和post

例如:

(1) 用Ajax异步载入一段html内容:
     //html:
        <input type="button" value="异步获取数据"/>
        <div id="box"></div>

        //jQuery

          $("input").click(function(){
             $("#box").load("test.html");
          });

(2)如果是服务器文件,比如.jsp。一般不仅需要载入数据,还需要向服务器提交数据,那么我们就可以使用第二个可选参数data.向服务器提交数据有两种方式:get和post

例如:

//客户端文件:post方式提交
     <script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
       <script type="text/javascript">
       $(function(){
          $("input").click(function(){
            $("#box").load("004.jsp",{url:"abc"});
         });
        });
     </script>
     </head>
     <body>
       <input type="button" value="异步获取数据" id="b1"/>
       <div id="box"></div>
     </body>
     </html>
//get方式提交:
     <script type="text/javascript">
       $(function(){
          $("input").click(function(){
            $("#box").load("004.jsp?url=abc"});
         });
        });
     </script>
//服务器端文件:004.jsp
  <body>
      <%
        String url=request.getParameter("url");
        if("abc".equals(url)){
      out.print("异步获取");
        }else{
       out.print("木有!");
        }

      %>
    </body>

(3)在Ajax数据载入完毕之后,就能执行回调函数callback,也就是第三个参数。回调函数也可以传递三个可选参数:

response(请求返回)、status(请求状态)、xhr(XMLHttpRequest对象) 。
  $(function(){
         $("input").click(function(){
            $("#box").load("004.jsp",{
               url:"abc"
           },function(response,status,xhr){
                alert("返回值为:"+response+",状态为:"+status);
            });
          });
       });  

注意:XMLHttpRequest对象的属性:

   responseText:返回的文本

   status:响应的http状态

   statusText:http状态的说明

http状态码:

   200   -->  OK  表示服务器成功返回了页面

   404   -->  Not found  指定的URL在服务器上找不到

   500   -->  Internal Server Error 服务器遇到意外错误,无法完成请求

load()方法是局部方法,因为他需要一个包含元素的jQuery对象作为前缀。而 . g e t ( ) .post()方法是全局方法,无需指定某个元素。对于用途而言,load()方法适合做静态文件的异步获取,而对于需要传递参数到服务器页面的, . g e t ( ) .post()方法更加适合。

(3)$.get()方法:

有四个参数,前面三个参数和load()方法一样,多了一个第四参数type,即服务器返回的内容格式:包括xml、html、script、json、jsonp和text。第一个参数为必选参数,后面三个为可选参数

例如:使用$.get()异步返回html类型
(1)用第二个参数data向服务器传递数据之一

     $(function(){
     $("input").click(function(){
       $.get("006.jsp",{url:'abc'},function(response,status,xhr){
         if(status=='success'){
            $("#box").html(response);
         }
           });
        });
         });

(2)用第二个参数data向服务器传递数据之二

          $("input").click(function(){
         $.get("006.jsp",'url=abc',function(response,status,xhr){
             if(status=='success'){
                $("#box").html(response);
             }
            });
         });

(3)使用”?”后带参数的方式向服务器传递数据:

      $("input").click(function(){
         $.get("006.jsp?url=abc",function(response,status,xhr){
             if(status=='success'){
                $("#box").html(response);
             }
            });
         });

(4)$.post()方法:

(1)用第二个参数data向服务器传递数据之一

     $(function(){
       $("input").click(function(){
         $.get("006.jsp",{url:'abc'},function(response,status,xhr){
         if(status=='success'){
            $("#box").html(response);
         }
           });
        });
          });

(2)用第二个参数data向服务器传递数据之二

    $("input").click(function(){
         $.get("006.jsp",'url=abc',function(response,status,xhr){
             if(status=='success'){
                $("#box").html(response);
             }
            });
         });

注意:第四参数type是指定异步返回的类型。一般情况下type参数是智能判断,并不需要我们主动设置,如果主动设置,则会强行按照指定类型格式返回。

猜你喜欢

转载自blog.csdn.net/hqh1129/article/details/80562168