Home > Web Front-end > JS Tutorial > body text

jQuery Ajax example full analysis

巴扎黑
Release: 2017-06-30 14:16:49
Original
1430 people have browsed it

jQuery is indeed a very good lightweight JS framework that can help us quickly develop JS applications and, to a certain extent, change our habit of writing JavaScript code.

    Without further ado, let’s get straight to the point. Let’s first look at some simple methods. These methods are all methods that encapsulate jQuery.ajax() for our convenience. Of course, If you want to handle complex logic, you still need to use jQuery.ajax() (this will be discussed later).

    1. load( url, [ data], [callback] ): Load the remote HTML file code and insert it into the DOM.

    #url (String): URL address of the requested HTML page.

    data (Map): (optional parameter) key/value data sent to the server.

    callback (Callback): (optional parameter) Callback function when the request is completed ( does not need to be of success).

    This method uses the GET method to pass by default. If the [data] parameter has data passed in, it will be automatically converted to the POST method. In jQuery 1.2, you can specify a selector to filter the loaded HTML document, and only the filtered HTML code will be inserted into the DOM. The syntax is "url #some > selector".

    This method can easily dynamically load some HTML files, such as forms.

    Sample code:

$("").load("",
 (responseText, textStatus, XMLHttpRequest){
; 
});
Copy after login

The results will be displayed here.

Note: I don’t know why writing an absolute path to a URL will cause an error under FF. If you know, please let me know. The get() and post() examples below use absolute paths, so under FF you will get an error and will not see the results returned. The get() and post() examples are both cross-domain calls. I found that there was no way to get the results after uploading them, so I removed the run button.

2. jQuery.get( url, [data], [callback] ): Use GET method for asynchronous Request

Parameters:

url (String): URL address to send the request.

data (Map): (Optional) The data to be sent to the server, expressed in the form of Key/value pairs, will be appended to the request URL as QueryString.

callback (Function): (Optional) Callback function when loading is successful (this method is called only when the return status of Response is success).

This is a simple GET request function to replace the complex $.ajax. The callback function can be called when the request is successful. If you need to execute a function on error, use $.ajax. Sample code:

 $.get("", {Action:"",Name:""},  (data, textStatus){
; (data);
});
Copy after login

Click to send a request:

This in the jQuery.get() callback function points to the option configuration information of the Ajax request:

jQuery Ajax example full analysis

3. jQuery.post( url, [data], [callback], [type] ): Use POST method Asynchronous request

Parameters:

url (String): URL address to send the request.

data (Map): (Optional) The data to be sent to the server, expressed in the form of Key/value pairs.

callback (Function): (Optional) Callback function when loading is successful (this method is called only when the return status of Response is success).

type (String) : (Optional) The official description is: Type of data to be sent. In fact, it should be the type of client request (JSON, XML, etc.)

This is a simple POST request function to replace the complex $.ajax. The callback function can be called when the request is successful. If you need to execute a function on error, use $.ajax. Sample code:

Ajax.aspx:

Response.ContentType = "";
Response.Write("" + Request[""] + "");
Copy after login
  • jQuery code:

  • $.post("", { Action: "", Name: "" },
     (data, textStatus){
    (data.result);
    }, "");
    Copy after login

    Click to submit:

    The request is set here The format is "json":

    jQuery Ajax example full analysis

    If you set the request format to "json", at this time you do not set the ContentType returned by Response to: Response.ContentType = "application /json"; then you will not be able to capture the returned data.

    Note that alert(data.result); Since the Accept header is set to "json", the data returned here is an object and does not need to be converted to using eval() object.

    4. jQuery.getScript( url, [callback] ): Request to load and execute a JavaScript file through GET method.

    Parameters

    url (String): The address of the JS file to be loaded.

    callback (Function) : (可选) 成功载入后回调函数。

    jQuery 1.2 版本之前,getScript 只能调用同域 JS 文件。 1.2中,您可以跨域调用 JavaScript 文件。注意:Safari 2 或更早的版本不能在全局作用域中同步执行脚本。如果通过 getScript 加入脚本,请加入延时函数。

    这个方法可以用在例如当只有编辑器focus()的时候才去加载编辑器需要的JS文件.下面看一些示例代码:

  • 加载并执行 test.js。

  • jQuery 代码:

    $.getScript("test.js");


    加载并执行 AjaxEvent.js ,成功后显示信息。

    jQuery 代码:

    $.getScript("", (){
    ("");
    });
    Copy after login

    加载完后请重新点击一下上面的 Load 请求看看有什么不同。

    jQuery Ajax 事件

    Ajax请求会产生若干不同的事件,我们可以订阅这些事件并在其中处理我们的逻辑。在jQuery这里有两种Ajax事件:局部事件 和 全局事件。

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

     $.ajax({
    beforeSend: (){
    },
    complete: (){
    }});
    Copy after login

    全局事件是每次的Ajax请求都会触发的,它会向DOM中的所有元素广播,在上面 getScript() 示例中加载的脚本就是全局Ajax事件。全局事件可以如下定义:

     $("").bind("", (){
    $().show();
    }).bind("", (){
    $().hide();
    });
    Copy after login

    或者:

     $("").ajaxStart((){
    $().show();
    });
    Copy after login

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

     $.ajax({
    url: "",
    global: ,});
    Copy after login

    下面是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.

      具体的全局事件请参考API文档。
      好了,下面开始说jQuery里面功能最强的Ajax请求方法 $.ajax();  

       

      jQuery.ajax( options ) : 通过 HTTP 请求加载远程数据

      这个是jQuery 的底层 AJAX 实现。简单易用的高层实现见 $.get, $.post 等。

      $.ajax() 返回其创建的 XMLHttpRequest 对象。大多数情况下你无需直接操作该对象,但特殊情况下可用于手动终止请求。

      注意: 如果你指定了 dataType 选项,请确保服务器返回正确的 MIME 信息,(如 xml 返回 "text/xml")。错误的 MIME 类型可能导致不可预知的错误。见 Specifying the Data Type for AJAX Requests 。
      当设置 datatype 类型为 'script' 的时候,所有的远程(不在同一个域中)POST请求都回转换为GET方式。

      $.ajax() 只有一个参数:参数 key/value 对象,包含各配置及回调函数信息。详细参数选项见下。

      jQuery 1.2 中,您可以跨域加载 JSON 数据,使用时需将数据类型设置为 JSONP。使用 JSONP 形式调用函数时,如 "myurl?callback=?" jQuery 将自动替换 ? 为正确的函数名,以执行回调函数。数据类型设置为 "jsonp" 时,jQuery 将自动调用回调函数。(这个我不是很懂)

      参数列表:

      参数名 类型 描述
      url String (默认: 当前页地址) 发送请求的地址。
      type String (默认: "GET") 请求方式 ("POST" 或 "GET"), 默认为 "GET"。注意:其它 HTTP 请求方法,如 PUT 和 DELETE 也可以使用,但仅部分浏览器支持。
      timeout Number 设置请求超时时间(毫秒)。此设置将覆盖全局设置。
      async Boolean (默认: true) 默认设置下,所有请求均为异步请求。如果需要发送同步请求,请将此选项设置为 false。注意,同步请求将锁住浏览器,用户其它操作必须等待请求完成才可以执行。
      beforeSend Function 发送请求前可修改 XMLHttpRequest 对象的函数,如添加自定义 HTTP 头。XMLHttpRequest 对象是唯一的参数。
       (XMLHttpRequest) {
      ; 
               }
      Copy after login
      cache Boolean (默认: true) jQuery 1.2 新功能,设置为 false 将不会从浏览器缓存中加载请求信息
      complete Function 请求完成后回调函数 (请求成功或失败时均调用)。参数: XMLHttpRequest 对象,成功信息字符串。
       (XMLHttpRequest, textStatus) {
      ; 
               }
      Copy after login
      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 对象,错误信息,(可能)捕获的错误对象。
       (XMLHttpRequest, textStatus, errorThrown) {
      
               ; 
               }
      Copy after login
      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 请求成功后回调函数。这个方法有两个参数:服务器返回数据,返回状态
       (data, textStatus) {
      
               ; 
               }
      Copy after login

      这里有几个Ajax事件参数:beforeSend success complete ,error 。我们可以定义这些事件来很好的处理我们的每一次的Ajax请求。注意一下,这些Ajax事件里面的 this 都是指向Ajax请求的选项信息的(请参考说 get() 方法时的this的图片)。
      请认真阅读上面的参数列表,如果你要用jQuery来进行Ajax开发,那么这些参数你都必需熟知的。

      示例代码,获取博客园首页的文章题目:

      $.ajax({
      type: "",
      url: "",
      beforeSend: (XMLHttpRequest){
      },
      success: (data, textStatus){
      $("").html("");
      $("",data).each((i, domEle){
      $("").append(""+$(domEle).children("").text()+"");
      });
      },
      complete: (XMLHttpRequest, textStatus){
      },
      error: (){
      }
      });
      Copy after login

      这里将显示首页文章列表。

       

       

      其他

      jQuery.ajaxSetup( options ) : 设置全局 AJAX 默认选项。

      设置 AJAX 请求默认地址为 "/xmlhttp/",禁止触发全局 AJAX 事件,用 POST 代替默认 GET 方法。其后的 AJAX 请求不再设置任何选项参数。

      jQuery 代码:

      $.ajaxSetup({
      url: "",
      global: ,
      type: ""
      });
      $.ajax({ data: myData });
      Copy after login

       

      serialize() 与 serializeArray()

      serialize() : 序列表表格内容为字符串。

      serializeArray() : 序列化表格元素 (类似 '.serialize()' 方法) 返回 JSON 数据结构数据。

      示例:

      HTML代码:

       =Results:   =SingleSingle2 = = =MultipleMultiple2 =Multiple3 = = = check1
       = = = 
      
      = check2
       = = = 
      
      = radio1
       = = = radio2
      Copy after login
    • serializeArray() 结果为:

      jQuery Ajax example full analysis

    The above is the detailed content of jQuery Ajax example full analysis. For more information, please follow other related articles on the PHP Chinese website!

    Related labels:
    source:php.cn
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!