Detailed explanation of jQuery Ajax

jQuery Ajax Detailed explanation

jQuery provides several functions for sending Ajax requests. The core and most complex one is jQuery.ajax( options ), all other Ajax functions are a simplified call of it. We can use this result when we want to fully control Ajax, otherwise it is more convenient to use simplified methods such as get, post, load, etc. So jQuery.ajax( options ) The method is introduced last. Let’s introduce the simplest load method first:

1. load( url, [data], [callback] )

Returns: jQuery wrapper set

Description:

The load method can load the remote HTML file code and insert it into the DOM.

The GET method is used by default. If the data parameter is passed, the Post method is used.

- When additional parameters are passed, it is 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 like "url #some > selector", and the default selector is "body>*".

Explanation:

load is the simplest Ajax function, but its use has limitations :

It is mainly used for the Ajax interface that directly returns HTML

load is a jQuery wrapper set method that needs to be called on the jQuery wrapper set and will load the returned HTML into the object. Even if the callback function is set, it will still load.

However, it is undeniable that the load interface is cleverly designed and simple to use. The following example demonstrates the use of the Load interface:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>jQuery Ajax - Load</title>
   <script type="text/javascript" src="../scripts/jquery-1.3.2-vsdoc2.js"></script>
    <script type="text/javascript">
        $(function()
        {
            $("#btnAjaxGet").click(function(event)
            {
                //发送Get请求
                $("#divResult").load("../data/AjaxGetMethod.aspx?param=btnAjaxGet_click" + "&timestamp=" + (new Date()).getTime());
            });
            $("#btnAjaxPost").click(function(event)
            {
                //发送Post请求
                $("#divResult").load("../data/AjaxGetMethod.aspx", { "param": "btnAjaxPost_click" });
            });
            $("#btnAjaxCallBack").click(function(event)
            {
                //发送Post请求, 返回后执行回调函数.
                $("#divResult").load("../data/AjaxGetMethod.aspx", { "param": "btnAjaxCallBack_click" }, function(responseText, textStatus, XMLHttpRequest)
                {
                    responseText = " Add in the CallBack Function! <br/>" + responseText
                    $("#divResult").html(responseText); //或者: $(this).html(responseText);
                });
            });
            $("#btnAjaxFiltHtml").click(function(event)
            {
                //发送Get请求, 从结果中过滤掉 "鞍山" 这一项
                $("#divResult").load("../data/AjaxGetCityInfo.aspx?resultType=html" + "&timestamp=" + (new Date()).getTime() + " ul>li:not(:contains('鞍山'))");
            });
        })
    </script>
</head>
<body>    
    <button id="btnAjaxGet">使用Load执行Get请求</button><br />
    <button id="btnAjaxPost">使用Load执行Post请求</button><br />
    <button id="btnAjaxCallBack">使用带有回调函数的Load方法</button><br />
    <button id="btnAjaxFiltHtml">使用selector过滤返回的HTML内容</button>
    <br />
    <div id="divResult"></div>
</body>
</html>

The above example demonstrates how Use the Load method.

Tip: We must always pay attention to the browser cache. When using the GET method, add the timestamp parameter (net Date()).getTime() to ensure that the URL is sent each time Different, you can avoid browser caching.

Tips: When a space is added after the url parameter, such as " ", an "unrecognized symbol" error will appear, but the request can still be sent normally. . But the HTML cannot be loaded into the DOM. The problem is solved after deletion.

2.jQuery.get( url, [data], [callback], [type] )

Returns: XMLHttpRequest

Description:

Load information through remote HTTP GET request .

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.

Explanation:

This function sends a Get request. The parameters can be spliced ​​directly in the url, such as:

$.get("../data/AjaxGetMethod.aspx?param=btnAjaxGet_click");

or through the data parameter Pass:

$.get("../data/AjaxGetMethod.aspx", { "param": "btnAjaxGet2_click" });

The two methods have the same effect. The data parameter will be automatically added to the requested URL.

If a parameter in the URL is passed through the data parameter, the same will not be automatically merged. The parameter of the name.

The signature of the callback function is as follows:

function (data, textStatus) {
  // data could be xmlDoc, jsonObj, html, text, etc...
  this; // the options for this ajax request
}

where data is the returned data, testStatus represents the status code, which may be the following values:

"timeout","error","notmodified","success","parsererror"

This in the callback function is a reference to the options object. For various instructions on options, please see:

http://docs.jquery.com/Ajax/jQuery.ajax#options

The type parameter refers to the type of data data, which may be the following values:

"xml", "html", "script", "json", "jsonp", "text".

The default is "html".

jQuery.getJSON(url, [data], [callback]) method is equivalent to jQuery.get(url, [data],[callback] ], "json")

3. jQuery.getJSON( url, [data], [callback] )

Returns: XMLHttpRequest

Equivalent to: jQuery.get(url, [data],[callback], "json")

Description:

Load JSON data through HTTP GET request.

In jQuery 1.2, you can load JSON data from other domains by using a callback function in the form of JSONP, such as "myurl?callback=?". jQuery will automatically replace ? with the correct function name to execute the callback function.

Note: The code after this line will be executed before this callback function is executed.

Explanation:

The getJSON function only sets the type parameter of the get function to "JSON". The data obtained in the callback function has been parsed according to the JSON format The object is:

$.getJSON("../data/AjaxGetCityInfo.aspx", { "resultType": "json" }, function(data, textStatus)
{
      alert(data.length);
      alert(data[0].CityName);
});

The string returned by the server is as follows:

[{""pkid"":""0997"",""ProvinceId"":"" XJ"",""CityName"":""Akesu"",""CityNameEn"":""Akesu"",""PostCode"":""843000"",""isHotCity"":false},

{""pkid"":""0412"",""ProvinceId"":""LN"",""CityName"":""Anshan"",""CityNameEn"" :""Anshan"",""PostCode"":""114000"",""isHotCity"":false}]

In the example I return an array, use data.length to get the array The number of elements, data[0] accesses the first element, data[0].CityName accesses the CityName attribute of the first element.

4.jQuery.getScript( url, [callback] )

Returns: XMLHttpRequest

is equivalent to: jQuery.get(url, null, [callback], "script")

Description:

Load and execute a JavaScript file through an HTTP GET request.

Before jQuery 1.2, getScript could only call JS files in the same domain. In 1.2, you can call JavaScript files across domains. Note: Safari 2 or earlier cannot execute scripts synchronously in the global scope. If you add a script via getScript, please add a delay function.

explain:

In the past, when I used the dojo class library, the official default files did not support cross-domain, which eventually led me to give up using dojo (although I found a cross-domain version on the Internet, but I felt it was not perfect). So I am particularly concerned about the core of this function. I have done research on the implementation and use.

First understand the jQuery internal implementation of this function, still using the get function. All jQuery Ajax functions including get finally use jQuery.ajax(), getScript The type parameter with the value "script" is passed in, and finally the request with type script is processed as follows in the Ajax function:

var head = document.getElementsByTagName("head")[0];            
var script = document.createElement("script");
script.src = s.url;

The above code dynamically creates a script statement block, and Add it to the head:

head.appendChild(script);

After the script is loaded, delete it from the head:

  // Handle Script loading
            if ( !jsonp ) {
                var done = false;
                // Attach handlers for all browsers
                script.onload = script.onreadystatechange = function(){
                    if ( !done && (!this.readyState ||
                            this.readyState == "loaded" || this.readyState == "complete") ) {
                        done = true;
                        success();
                        complete();
                        // Handle memory leak in IE
                        script.onload = script.onreadystatechange = null;
                        head.removeChild( script );
                    }
                };
            }

Mainly tested the cross-domain access and multiple functions of this function Browser support. Here are the results:

##IE6FireFoxNote MatterPassedPassed Both data and textStatus in the callback function are available Cross-domain reference jsThrough Through the callback function The data and textStatus in are both undiffed

The following are the key test statements, which are also used to demonstrate how to use the getScript function:

  $("#btnAjaxGetScript").click(function(event)
            {
                $.getScript("../scripts/getScript.js", function(data, textStatus)
                {
                    alert(data);
                    alert(textStatus);
                    alert(this.url);
                });
            });
            $("#btnAjaxGetScriptCross").click(function(event)
            {
                $.getScript("http://resource.elong.com/getScript.js", function(data, textStatus)
                {
                    alert(data);
                    alert(textStatus);
                    alert(this.url);
                });
            });

5. jQuery.post( url, [data], [callback], [type ] )

Returns: XMLHttpRequest

Description:

Load information through remote HTTP POST request.

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.

Explanation:

The specific usage is the same as get, except that the submission method is changed from "GET" to "POST".

6. jQuery.ajax( options )

Returns: XMLHttpRequest

Description:

Load remote data via HTTP requests.

jQuery underlying AJAX implementation. For simple and easy-to-use high-level implementations, see $.get, $.post, etc.

$.ajax() returns the XMLHttpRequest object it created. In most cases you will not need to manipulate this object directly, but in special cases it can be used to manually terminate the request.

$.ajax() has only one parameter: parameter key/value object, including each configuration and callback function information. See detailed parameter options below.

Note: If you specify the dataType option, make sure the server returns the correct MIME information (such as xml returns "text/xml"). Incorrect MIME types can cause unpredictable errors. See Specifying the Data Type for AJAX Requests.

Note: If dataType is set to "script", then all remote (not under the same domain name) POST requests will be converted into GET requests. (Because the DOM script tag will be used to load)

In jQuery 1.2, you can load JSON data across domains, and you need to set the data type to JSONP when using it. When calling a function using JSONP form, such as "myurl?callback=?" jQuery will automatically replace ? with the correct function name to execute the callback function. When the data type is set to "jsonp", jQuery will automatically call the callback function.

Explanation:

This is the core function of Ajax in jQuery. All the functions above that send Ajax requests will eventually call this function. The options parameter supports many parameters. Using these parameters can completely control the ajax request. The this object in the Ajax callback function is also the options object.

Because the simplified get and post functions are most commonly used, the options parameters are not used here. Explained in detail.

Continuing Learning
||
<!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-3.1.1.min.js"></script> <script> $(document).ready(function(){ $("#btn1").click(function(){ $('#test').load('/asset/demo.ajax.php?dm=txt&act=getfruits'); 可以自定义文本内容! }) }) </script> </head> <body> <h3 id="test">请点击下面的按钮,通过 jQuery AJAX 改变这段文本。</h3> <button id="btn1" type="button">获得外部的内容</button> </body> </html>
submitReset Code

Non-cross-domain reference js