zoukankan      html  css  js  c++  java
  • jQuery学习笔记(Ajax)

    jQuery对Ajax操作进行了封装,在jQuery中$.ajax方法属于最底层的方法,第2层是$.load()、$.get()、$.post()方法,第3层是$.getScript()和$.getJSON()方法。

    1. $.load(url [,data] [,callback])方法,载入HTML文档

    - url (String) : 请求HTML页面的URL地址
    - data (Object) : (可选) 发送至服务器的 key/value 对
    - callback (Function) : (可选) 请求完成时的回调函数(成功、失败都调用)

    简单示范:

      $(function(){
          $("#send").click(function(){
              $("#resText").load("test.html");
          })
      })

    同时,load()方法可以筛选载入的HTML文档,URL参数语法结构为:“url selector“。示范:

      $(function(){
          $("#send").click(function(){
                 $("#resText").load("http://www.cnblogs.com/nayitian/archive/2013/01/18/2866667.html .post");
          })
      })

    load()方法的传递方式根据参数data自动指定。如果没有参数传递,则采用get方式传递;反之,则会自动转换为post方式。

    回调函数必须在加载完成后才能继续操作。示范如下:

    $(function(){
        $("#send").click(function(){
            $("#resText").load("test.html .para",function (responseText, textStatus, XMLHttpRequest){
                alert( $(this).html() );    //在这里this指向的是当前的DOM对象,即 $("#iptText")[0]
                alert(responseText);       //请求返回的内容
                alert(textStatus);            //请求状态:success,error
                alert(XMLHttpRequest);     //XMLHttpRequest对象
            });
        })
    })

    2. $.get(url [,data] [,callback] [,type])方法

    - url (String) : 请求HTML页面的URL地址
    - data (Object) : (可选) 发送至服务器的 key/value 对,作为QueryString附加到请求URL中
    - callback (Function) : (可选)载入成功时回调函数(只有当Reponse的返回状态是success才调用),自动将请求结果和状态传递给该方法
    - type (String) : (可选) 服务器端返回内容的格式,包括:xml/html/script/json/text/_default

    2.1 示范一,返回HTML格式的数据(后台代码略)

    $(function(){
        $("#send").click(function(){
            $.get("get1.jsp", { 
                username :  encodeURI( $("#username").val() ) , 
                content :   encodeURI( $("#content").val() ) 
            }, function (data, textStatus){
                $("#resText").html(  decodeURI(data) ); // 把返回的数据添加到页面上
            }
            );
        })
    })

    2.2 示范二,返回XML格式数据

    调用页面:

    $(function(){
        $("#send").click(function(){
            $.get("get2.jsp", { 
                username :  encodeURI( $("#username").val() ) , 
                content :   encodeURI( $("#content").val() ) 
            }, function (data, textStatus){
                var username = $(data).find("comment").attr("username");
                var content = $(data).find("comment content").text();
                username =  decodeURI(username);
                content = decodeURI(content);
                var txtHtml = "<div class='comment'><h6>"+username+":</h6><p class='para'>"+content+"</p></div>";
                $("#resText").html(txtHtml); // 把返回的数据添加到页面上
            });
        })
    })

    后台JSP页面(注意最好别留换行符,否则前台可能不能正常解析):

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%
      String username = request.getParameter("username");
      String content = request.getParameter("content");
      response.setContentType("text/xml");
      out.println("<?xml version='1.0' encoding='UTF-8'?>");
      out.println("<comments>");
      out.println("<comment username='"+username+"'>");
      out.println("<content>"+content+"</content>");
      out.println("</comment>");
      out.println("</comments>");
    %>

    2.3 示范三,返回JSON格式数据

    调用页面:

    $(function(){
        $("#send").click(function(){
            $.get("get3.jsp", { 
                username :  encodeURI( $("#username").val() ) , 
                content :   encodeURI( $("#content").val() ) 
            }, function (data, textStatus){
                var username = data.username;
                var content = data.content;
                username =  decodeURI(username);
                content = decodeURI(content);
                var txtHtml = "<div class='comment'><h6>"+username+":</h6><p class='para'>"+content+"</p></div>";
                $("#resText").html(txtHtml); // 把返回的数据添加到页面上
            },"json");
        })
    })

    后台JSP页面(JSON串必须用双引号,不打引号或用单引号都有问题):

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%
      String username = request.getParameter("username");
      String content = request.getParameter("content");
      // 必须用双引号,不打引号或用单引号都有问题
      out.println("{"username":""+username+"","content":""+content+""}");
    %>

    3. $.post(url [,data] [,callback] [,type])方法

    它与$.get()方法的结构和使用方式都相同,存在如下区别:

    • get请求会将参数紧跟在URL后进行传递,而post请求则是作为HTTP消息的实体内容发送给Web服务器。
    • get方式对传输在数据有大小限制(通常不以大于2kb),而使用post方式传递数据理论上不受限制。
    • get方式请求的数据会被游览器缓存起来,有可能带来安全性问题,而post不存在此问题。
    • get与post服务器端获取也有些差别(用request获取例外)。

    4. $.getScript()方法与$.getJSON()方法

    jQuery提供了$.getScript()方法来直接加载.js文件,与加载一个HTML片段一样简单方便,并且不需要对JavaScript进行处理,JavaScript文件会自动执行。

    jQuery 1.2版本之前,getScript()只能调用同域 JS文件。 1.2之后,可以跨域调用JavaScript文件。

       $(function(){
            $('#send').click(function() {
                 $.getScript('test.js');
            });
       })

    $.getJSON()方法用于加载JSON文件,与$.getScript()方法的用法相同。

    $(function(){
        $('#send').click(function() {
            $.getJSON('test.json', function(data) {
                $('#resText').empty();
                var html = '';
                $.each( data  , function(commentIndex, comment) {
                    html += '<div class="comment"><h6>' + comment['username'] + ':</h6><p class="para">' + comment['content'] + '</p></div>';
                })
                $('#resText').html(html);
            })
        })
    })

    5. $.ajax()方法

    $.ajax()方法是jQuery最底层的Ajax实现,结构:$.ajax(options),该方法只有一个参数,但在这个对象里包含了$.ajax()方法所需要的请求设置以及回调函数等信息,参数以key/value的形式存在 ,所有参数都是可选的。

    前面用到的$.load()、$.get()、$.post()、$.getScript()、$.getJSON()这些方法,都是基于$.ajax()方法构建的。

    常用参数如下表:

    参数名

    类型

    描述

    url

    String

    (默认: 当前页地址) 发送请求的地址。

    type

    String

    请求方式 ("POST" 或 "GET"), 默认为 "GET"。注意:其它 HTTP 请求方法,如 PUT 和 Delete 也可以使用,但仅部分浏览器支持。

    timeout

    Number

    设置请求超时时间(毫秒)。此设置将覆盖全局设置。

    async

    Boolean

    (默认: true) 默认设置下,所有请求均为异步请求。如果需要发送同步请求,请将此选项设置为 false。注意,同步请求将锁住浏览器,用户其它操作必须等待请求完成才可以执行。

    beforeSend

    Function

    发送请求前可修改 XMLHttpRequest 对象的函数,如添加自定义 HTTP 头。XMLHttpRequest 对象是唯一的参数。

    function (XMLHttpRequest) {  

        this; // 调用本次Ajax请求时传递的options参数

    }

    cache

    Boolean

    (默认: true) jQuery 1.2 新功能,设置为 false 将不会从浏览器缓存中加载请求信息。

    complete

    Function

    请求完成后回调函数 (请求成功或失败时均调用)。参数: XMLHttpRequest 对象,成功信息字符串。

    function (XMLHttpRequest, textStatus) {  

        this; // 调用本次Ajax请求时传递的options参数

    }

    contentType

    String

    (默认: "application/x-www-form-urlencoded") 发送信息至服务器时内容编码类型。默认值适合大多数应用场合。

    data

    Object, String

    发送到服务器的数据。将自动转换为请求字符串格式。GET 请求中将附加在 URL 后。查看 processData 选项说明以禁止此自动转换。必须为 Key/Value 格式。如果为数组,jQuery 将自动为不同值对应同一个名称。如 {foo:["bar1", "bar2"]} 转换为 '&foo=bar1&foo=bar2'。

    dataType

    String

    预期服务器返回的数据类型。如果不指定,jQuery 将自动根据 HTTP 包 MIME 信息返回 responseXML 或 responseText,并作为回调函数参数传递,可用值:

    "xml": 返回 XML 文档,可用 jQuery 处理。

    "html": 返回纯文本 HTML 信息;包含 script 元素。

    "script": 返回纯文本 JavaScript 代码。不会自动缓存结果。

    "json": 返回 JSON 数据 。

    "jsonp": JSONP 格式。使用 JSONP 形式调用函数时,如 "myurl?callback=?" jQuery 将自动替换 ? 为正确的函数名,以执行回调函数。

    error

    Function

    (默认: 自动判断 (xml 或 html)) 请求失败时将调用此方法。这个方法有三个参数:XMLHttpRequest 对象,错误信息,(可能)捕获的错误对象。

    function (XMLHttpRequest, textStatus, errorThrown) {  

        // 通常情况下textStatus和errorThown只有其中一个有值  

        this; //调用本次Ajax请求时传递的options参数

    }

    global

    Boolean

    (默认: true) 是否触发全局 AJAX 事件。设置为 false 将不会触发全局 AJAX 事件,如 ajaxStart 或 ajaxStop 。可用于控制不同的Ajax事件

    ifModified

    Boolean

    (默认: false) 仅在服务器数据改变时获取新数据。使用 HTTP 包 Last-Modified 头信息判断。

    processData

    Boolean

    (默认: true) 默认情况下,发送的数据将被转换为对象(技术上讲并非字符串) 以配合默认内容类型 "application/x-www-form-urlencoded"。如果要发送 DOM 树信息或其它不希望转换的信息,请设置为 false。

    success

    Function

    请求成功后回调函数。这个方法有两个参数:服务器返回数据,返回状态

    function (data, textStatus) {  

        // data could be xmlDoc, jsonObj, html, text, etc...    

        this; // 调用本次Ajax请求时传递的options参数

    }

     5.1 下述代码取代$.getScript()方法

       $(function(){
            $('#send').click(function() {
                $.ajax({
                  type: "GET",
                  url: "test.js",
                  dataType: "script"
                }); 
            });
       })

    5.2 下述代码取代$.getJSON()方法

       $(function(){
            $('#send').click(function() {
                $.ajax({
                  type: "GET",
                  url: "test.json",
                  dataType: "json",
                  success : function(data){
                     $('#resText').empty();
                      var html = '';
                      $.each( data  , function(commentIndex, comment) {
                          html += '<div class="comment"><h6>' + comment['username'] + ':</h6><p class="para">' + comment['content'] + '</p></div>';
                      })
                     $('#resText').html(html);
                  }
                }); 
            });
       })

    5.3 跨域调用示范

    $(function(){
        $('#send').click(function() {
            $.ajax({
              type: "GET",
              url: "http://api.flickr.com/services/feeds/photos_public.gne?tags=car&tagmode=any&format=json&jsoncallback=?",
              dataType: "jsonp",
              success : function(data){
                  $.each(data.items, function( i,item ){
                        $("<img class='para'/> ").attr("src", item.media.m ).appendTo("#resText");
                        if ( i == 3 ) { 
                            return false;
                        }
                  });
              }
            }); 
        });
    })

    6. serialize()方法、serializeArray()方法、param()方法

    6.1 serialize()方法

    serialize()方法能够将DOM元素内容序列化为字符串,用于Ajax请求,此方法还可以自动编码,以避免编码带来的问题。示范:

    $(function(){
       $("#send").click(function(){
            $.post("get1.jsp", $("#form1").serialize() , function (data, textStatus){
                    $("#resText").html(data); // 把返回的数据添加到页面上
                }
            );
       })
    })

    serialize()方法可以表单进行过滤,如:

    $(function(){
       $("#send").click(function(){
            var $data =  $(":checkbox,:radio").serialize();
            alert( $data );
       })
    })

    6.2 serializeArray()方法

    serializeArray()方法不是返回字符串,而是将DOM对象序列化后,返回JSON格式的数据,示范:

    $(function(){
         var fields = $(":checkbox,:radio").serializeArray();
         console.log(fields);// Firebug输出
         $.each( fields, function(i, field){
            $("#results").append(field.value + " , ");
        }); 
    })

    6.3 param()方法

    它是serialize()方法的核心,用来对一个数组或对象按照key/value进行序列化。

    $(function(){
        var obj={a:1,b:2,c:3};
        var  k  = $.param(obj);
        alert(k)        // 输出  a=1&b=2&c=3
    })

    7. Ajax事件

    jQuery简化Ajax操作不仅体现在调用Ajax方法和处理响应方面,而且还体现在对调用Ajax方法的过程中的HTTP请求的控制。通过jQuery提供的一些自定义全局函数,能够为各种Ajax相关的事件注册回调函数。

    在jQuery这里有两种Ajax事件:“局部事件”和“全局事件”。

    局部事件就是在每次的Ajax请求时在方法内定义的,比如:

    $.ajax({
        beforeSend: function(){
            // Handle the beforeSend event
        },
        complete: function(){
            // Handle the complete event
        }
        // ...
    });

    全局事件是每次的Ajax请求都会触发的,它会向DOM中的所有元素广播,比如,装载一个页面时,在开始装载提示“加载中...“;装载完毕,提示消失;以增加用户体验。示范:

    <div id="loading">加载中...</div>
       $("#loading").ajaxStart(function(){
          $(this).show();
       });
       $("#loading").ajaxStop(function(){
          $(this).hide();
       });

    我们可以在特定的请求将全局事件禁用,只要设置下 global 选项就可以了:

     $.ajax({
        url: "test.html",
        global: false,// 禁用全局Ajax事件.
        // ...
    });

    下面是jQuery官方给出的完整的Ajax事件列表:

    • ajaxStart (Global Event) This event is broadcast if an Ajax request is started and no other Ajax requests are currently running.
    • beforeSend (Local Event)      This event, which is triggered before an Ajax request is started, allows you to modify the XMLHttpRequest object (setting additional headers, if need be.)     
    • ajaxSend (Global Event)      This global event is also triggered before the request is run.     
    • success (Local Event)      This event is only called if the request was successful (no errors from the server, no errors with the data).     
    • ajaxSuccess (Global Event)      This event is also only called if the request was successful.     
    • error (Local Event)      This event is only called if an error occurred with the request (you can never have both an error and a success callback with a request).     
    • ajaxError (Global Event)      This global event behaves the same as the local error event.     
    • complete (Local Event)      This event is called regardless of if the request was successful, or not. You will always receive a complete callback, even for synchronous requests.     
    • ajaxComplete (Global Event)      This event behaves the same as the complete event and will be triggered every time an Ajax request finishes.
    • ajaxStop (Global Event) This global event is triggered if there are no more Ajax requests being processed.
  • 相关阅读:
    DLL编写中extern “C”和__stdcall的作用
    spring mvc controller中的异常封装
    springMVC 【@response 返回对象自动变成json并且防止乱码】 & 【配置支持实体类中的@DateTimeFormat注解】
    Eclipse中修改SVN用户名和密码方法
    Maven
    j2ee、mvn、eclipse、Tomcat等中文乱码问题解决方法
    maven生成jar包
    windows超过最大连接数解决命令
    spring 国际化-i18n
    springMVC 前后台日期格式传值解决方式之二(共二) @InitBinder的使用
  • 原文地址:https://www.cnblogs.com/nayitian/p/3380126.html
Copyright © 2011-2022 走看看