Beginner Ajax (i)

Source: Internet
Author: User

The following text is organized according to Eon--jquery tutorial.

Ajax is all called: "Asynchronous JavaScript and XML" (Asynchronous JavaScript and XML), which is not a single technology of JavaScript, but a combination of a series of interactive Web application-related technologies. With Ajax, we can update the page without refreshing the status and implement asynchronous commit, which improves the user experience.

Ajax Overview

The concept of Ajax was invented by Jesse James Garrett in 2005. It is not a single technology in itself, it is a collection of technologies, mainly:

    1. JavaScript, which captures interactive behavior through user or other browser-related events
    2. A XMLHttpRequest object that enables you to send requests to the server without interrupting other browser tasks
    3. Files on the server, saving text data in XML, HTML, or JSON format
    4. Other JavaScript that interprets data from the server (such as PHP's data obtained from MySQL) and renders it on the page

Because Ajax contains many features, the advantages and disadvantages are also obvious. The main advantages of the following points:

    1. No plug-in support required (general browser and JavaScript enabled by default)
    2. Excellent user experience (no page refresh to get updatable data)
    3. Improve the performance of your Web program (send data on demand, without having to submit it as a whole)
    4. Offload server and bandwidth (transfer some of the server's operations to the client)

And the lack of Ajax has the following points:

    1. Different versions of browsers have insufficient support for XMLHttpRequest objects (e.g. before IE5)
    2. The function of forward and backward is destroyed (because Ajax is always on the current page and does not remember the front and back pages)
    3. Search engine support is not enough (because the search engine crawler can not understand the content of JS caused change data)
    4. Lack of development debugging tools (compared to other language toolset, JS or Ajax debugging development less poor)

Asynchronous and synchronous

The most critical place to use Ajax is to implement asynchronous requests, accept responses, and execute callbacks. So what's the difference between asynchronous and synchronous? Our common Web program development is basically synchronous, meaning to execute a program in order to execute the next paragraph, similar to the call in the phone, a call to answer the next call, and asynchronous can execute multiple tasks at the same time, feel that there are many lines, similar to text messages, not because of reading a text message and stop accepting another text message. Ajax can also be executed using synchronous mode, but the mode of synchronization is blocking mode , which will cause the execution of multiple lines and must be a single execution, the Web page will appear suspended animation , so the general Ajax mostly use asynchronous mode.

Load Method

jquery does a lot of encapsulation of Ajax, and we use it more conveniently, without having to consider browser compatibility. For encapsulation, jquery uses a three-layer package: The lowest-level package is:$.ajax (), while the second layer is encapsulated by this layer, there are three ways:. Load (),$.get () , and $. Post (), the highest layer is the $.getscript () and the $.getjson () method.

The. Load () method can pass three parameters: URL (must, request HTML file URL address, parameter type is string), data (optional, send key/value data, parameter type is Object), callback (optional, A successful or failed callback function that has a parameter type of function.

If you want Ajax to load an HTML content asynchronously, we just need a URL for the HTML request.

The ajax.html code is as follows:

<!DOCTYPE HTML><HTML><Head>    <MetaCharSet= "UTF-8">    <title>Ajax</title>    <Scripttype= "Text/javascript"src= "Jquery-1.12.3.js"></Script>    <Scripttype= "Text/javascript"src= "Demo.js"></Script>    <Linkrel= "stylesheet"type= "Text/css"href= "Style.css" /></Head><Body>    <inputtype= "button"value= "Load data asynchronously" />    <DivID= "box">            </Div></Body></HTML>

To load the data asynchronously, test.html:

<class= "title"> Dipper City Web Club </span> <  class= "url">www.ycku.com</span  >

jquery Code:

$ ("Input"). Click (function() {    $ ("#box"). Load ("test.html");});

If you want to filter the loaded HTML, simply follow the URL parameter followed by a selector.

$ ("Input"). Click (function() {    $ (// URL with selector});

If it's a server file, like. php ( hell, never learned it). It is not only necessary to load data, but also to submit data to the server, so we can use the Second optional parameter, data. There are two ways to submit data to the server: Get and post.

$ ("Input"). Click (function() {    $ (// do not pass data, the default get mode });

Get mode accepted PHP ( not learned PHP, this is a problem )

<? PHP     if ($_get[' url '] = = ' Ycku ')        {echo "Dipper City Web Club"    ; Else {        echo "Wood has! ";    }? >
$ ("Input"). Click (function() {    $ ("#box"). Load ("test.php", {  //  Pass data, then the Post method        URL: "Ycku"    }) ;

Post-mode accepted PHP:

<? PHP     if ($_post[' url '] = = ' Ycku ')        {echo "Dipper City Web Club"    ; Else {        echo "Wood has! ";    }? >

After the AJAX data is loaded, you can execute the callback function callback, which is the third parameter. The callback function can also pass three optional parameters: ResponseText (Request return), Textstatus (Request state), XMLHttpRequest (XMLHttpRequest object).

The jquery code is as follows:

$ ("Input"). Click (function() {    $("#box"). Load ("test.php"), {URL:"Ycku"    }, function(response, status, XHR) {//alert (response);//return response        //$ ("#box"). HTML (response+ "123");        //alert (status);        //if (status = = "Success") {        //alert ("Post-success processing");        // }                    //alert (xhr.responsetext);//Xhr.responsetext equivalent to response        //alert (xhr.responsexml);//undefined        //alert (xhr.status);//200alert (Xhr.statustext);//OK    });});

Note: The status gets the value if the data returned successfully is: success, otherwise: error. The XMLHttpRequest object belongs to the JavaScript category, and some properties can be called as follows:

Property name Description
ResponseText Text to be returned as the response body
Responsexml If the response principal content type is "Text/xml" or "Applicaton/xml", the XML DOM document containing the response data is returned
Status HTTP status of the response
StatusText Description of the HTTP status

If the data is returned successfully, then the StatusText property of the Xhr object returns the ' OK ' string. In addition to the ' OK ' status string, the StatusText property also provides a series of other values, as follows:

HTTP status Code Status string Description
200 Ok The server successfully returned the page
400 Bad Request Syntax error causes server not to recognize
401 Unauthorized Request requires user authentication
50U Not found The specified URL could not be found on the server
500 Internal Server Error The server encountered an unexpected error and could not complete the request
503 Serviceunavailable Unable to complete request due to server overload or maintenance

Beginner Ajax (i)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.