Ajax Use Learning __ajax

Source: Internet
Author: User

First, Introduction

1. Ajax is the abbreviation for asynchronous Javascript and XML, which means performing asynchronous network requests

2, we will find that using Form form submission button submit the form, the page will have to perform a refresh operation, the new page to inform the operation results, and Ajax technology can make the request data to the server without unloading the page , get a better experience

3,the core of Ajax is the XMLHttpRequest object , it implements the asynchronous way from the server to obtain data, that is, using the XHR object to obtain the server data, and then use the DOM to update the data to the page

4, although the AJAX name contains XML, but he is only a means of communication, and the specific data format is not related to, because the mainstream use of XML as the front and back communication data format, so the name of the use of XML, and now mainly used in JSON format strings second, the XMLHttpRequest object the implementation process of Ajax is as follows: create XHR object Invoke open () method, create request call Send () method, send request capture request status, Judge request result get data returned by database 1, create xhr object

XHR object is the first implementation of the IE5, at that time, the use of ActiveX objects, so xhr under IE there are two versions of the implementation, IE7 the following ActiveX objects and IE7 and above XHR objects, the rest of the browser is a unified use of the XHR object

So when you create an object, you need a compatibility notation.

if (window. XMLHttpRequest) {
    var request = new XMLHttpRequest ();
} else{
    //This is IE7 the following writing
    var request = new ActiveXObject ("Microsoft.XMLHTTP");
}

2. Call Open () method

Request.open (Method,url,boolean);
The Open () method receives 3 parametersMethod: Data submission, in the form of a string, that can use the "get" or "POST" URL: Request object address, string representation (get way differs from post mode) Boolean:true (default) represents an asynchronous request. False indicates synchronous requests (which are believed to be asynchronous using Ajax, so this is true, or not filled in) Get Mode request

Submitting data in a get way requires that the submission be appended to the URL in a fixed format, in the following format:
url = "Address?" Name1=value1 & Name2=value2 ";

Gets the input box to the username and password
var username = document.getElementById ("username");
var passwd = document.getElementById ("passwd");
Append the input to the URL after the
var url = "Php/get.php?username=" +username.value+ "&passwd=" +passwd.value;
Call the Open () method
Request.open ("Get", url,true);
Post mode request

Submit the data using post, the submission is submitted as a parameter to the Send () method, so no additional parameters are required after the URL

Gets the input box to the username and password
var username = document.getElementById ("username");
var passwd = document.getElementById ("passwd");
Append the input to the URL after the
var url = "php/post.php";
Call the Open () method
Request.open ("Post", url,true);

Note: Because the form form is no longer used, the background cannot use the Name property to get the data, and the content defined in the Form Form Name property is now in the name1 in name1=value1, corresponding, The Post method is the Name1 3 in the postbody below , and the call to send () method

Request.send (Postbody);
The Send () method receives 1 parametersPostbody: In string form, fill in the data that needs to be submitted, if no data is submitted, you can fill in null Get Mode request

Because the data in the Get mode is already attached to the URL after the submission, so here generally fill in the null POST method request

The format of the data is as follows:
Postbody = "Name1=value1 & Name2=value2";

Gets the input box to the username and password
var username = document.getElementById ("username");
var passwd = document.getElementById ("passwd");
Append the input to the URL
var postbody = "Username=" +username.value+ "&passwd=" +passwd.value;
Call Send () method
request.send (postbody);

Note 1: Here, post-submit data is different from submitting form forms, and the server needs a program to read and parse the raw data, so we need to use XHR to mimic the form submission:

Reset    
//define the content type for the form submission, and create a string request.setrequestheader with the appropriate type    ("Content-type", "application/ X-www/form-unencoded ");

Note 2: This method can only be added after the open () method, before the Send () method

The actual use method
var username = document.getElementById ("username");
var passwd = document.getElementById ("passwd");

var url = "php/post.php";    
Request.open ("Post", url,true);

Place the position must be here
request.setrequestheader ("Content-type", "application/x-www/form-unencoded");

var postbody = "Username=" +username.value+ "&passwd=" +passwd.value;
Request.send (Postbody);
4, capture request status, judge the result

After the Send () method is invoked, the request is committed to the server; In most cases, we send an asynchronous request to check the current active phase of the request process before determining whether the request returns a successful XHR object-related attribute: readyState: The current active phase of the request/corresponding process ResponseText: The text returned as a response body Responsexml: If the corresponding content type is Text/xml or application this property will hold the XMLDOM document status of the response data: the corresponding HTTP status Statustext:http states indicate that we use native onreadystatechange events to monitor readystate changes readystate return values are as follows: ReadyState return value


Whenever a value of readystate changes to another value, a onreadystatechange event is triggered, which can be used to return the request/Response process status value of the monitor

We are concerned about the situation where the value of readystate is 4, because it represents all the data is ready, and if the status returns, you can determine that the request/response process is complete with the status return value as follows: Status return value


Note: Do not use statustext to determine this, because this value is not reliable across browsers

The final return result, no matter what type of content, will be saved in the ResponseText code as follows:

Monitor readyState status and status return value
Request.onreadystatechange = function () {
    if (request.readystate = 4 && Request.status = =) {
        alert (request.responsetext);
    }
}


To sum up the content, is the entire AJAX request all the process, we in JS finally got is the backstage return responsetext, only inside saves in general is the JSON format string , we may convert it to the array or the object after extracting the key value of the three, encapsulation use the following code is the process of the above encapsulation, so that when used as long as the call function and in the callback function to implement the function can be

 <script> * * method is the request mode * URL is the address of the network request * Postboidy is the post mode request for the submission of data * Successcallback is the function of the request success * Errorcallback is please Fail function request (Method,url,postbody,successcallback,errorcallback) {//Create a Request object if window.
    XMLHttpRequest) {var request = new XMLHttpRequest ();
    }else{var request = new ActiveXObject ("Microsoft.XMLHTTP");
        } if (arguments[0]== "POST") {//Create request Request.open (method,url,true);
    Set Upload type Request.setrequestheader ("Content-type", "application/x-www-form-urlencoded");
    }else if (arguments[0]== "get") {Request.open (method,url,true);
    }//Send request Request.send (postbody); 
            state Listener Request.onreadystatechange = function () {if (request.readystate ==4 && request.status = = 200) {
            The request succeeds callback function if (successcallback) {successcallback (request.responsetext); } else if (request.readystate = 4 && Request.statuS!= 200) {//Request failed callback function if (errorcallback) {errorcallback (request.statustext); {}}}} </script>
examples of how to use:

The following defines a simple form submission user name and password, using the callback function to retrieve the back of the JSON string, converted to objects and then remove the information, tell the user is landing success or failure

HTML part//Call encapsulated function <script src= "request.js" ></script> <div class= "form" > <input type= "text" id= " 

Username "> <input type=" password "id=" passwd "> <button id=" loginbtn "> Login </button> </div>
JS section <script> var username = document.getElementById ("username");
var passwd = document.getElementById ("passwd"); var loginbtn = document.getElementById ("loginbtn") Loginbtn.onclick = function () {//Set request address and submit content var url = "Login
    . php ";
    var postbody = "Username=" +username.value+ "&passwd=" +passwd.value; Initiate an AJAX request and use a callback function to implement the function request ("POST", Url,postbody,function (ResText) {//Convert the JSON-formatted string to object var obj = J
        Son.parse (ResText);
    alert (obj.msg);
});
    </script>//php Part login.php <?php//Get user name and password from request $username = $_post["username"];
    $passwd = $_post["passwd"];
    Connect to server @ $mysqli = new Mysqli ("localhost", "root", "", "user");
    $mysqli->query ("Set names UTF8"); CheckQuery $sql = "SELECT * from user WHERE username= ' $username ' and passwd= ' $passwd '";
    Database execution Query $result = $mysqli->query ($sql); Determine if the query result has a value, and define the return string//echo out is the data that returns the front End if ($result->num_rows > 0) {echo ' {"ErrorCode": 0, "msg": "Landing successful
    "}';
    }else{echo ' {' errorcode ': 1, ' msg ': ' Username or password error '} '; //Shut down the server $mysqli->close ();?>


Author: Xiao Pxu
Link: http://www.jianshu.com/p/ff9e1139ea51
Source: Jianshu
Copyright belongs to the author. Commercial reprint please contact the author to obtain authorization, non-commercial reprint please indicate the source.


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.