Native Ajax Request Tutorial

Source: Internet
Author: User

ajaxThat is Asynchronous Javascript And XML,AJAX , not a new language, but the comprehensive utilization of existing holding technique. The essence is to communicate with the server asynchronously, based on the HTTP protocol.

Async: means that a program executes without blocking other program execution, in the form of a program's order of execution that does not depend on the writing order of the program itself, but rather on synchronization.

XMLHttpRequest Object

Browser-built objects for communicating with the server in the background (exchanging data), so that we can implement a partial update of the Web page instead of refreshing the entire page.

All modern browsers (ie7+, Firefox, Chrome, Safari, and Opera) have built-in XMLHttpRequest objects.

var xhr = new XMLHttpRequest();

Older versions of Internet Explorer (IE5 and IE6) use ActiveX objects:
var xhr=new activexobject ("Microsoft.XMLHTTP");

To send the request to the server, we use XMLHttpRequest the object's open() and send() method:

var xhr = new XMLHttpRequest();xhr.open(‘GET‘, ‘ajax_info.json‘, true);xhr.send();
Method Description
Open (Method,url,async) Specifies the type of request, the URL, and whether the request is processed asynchronously.
Method: type of request; GET or POST
URL: The location of the file on the server
Async:true (asynchronous) or false (synchronous)
Send (String) Sends the request to the server. String: Only for POST requests
GET request

The GET request parameters need to be placed in the parameters of the URL address. And through the way of UrlEncode, that is, to ? separate the URL and parameters, and then a number of parameters with & the connection, the parameter format is: key=val .

var xhr = new XMLHttpRequest();xhr.open("GET","/ajax.php?fname=Henry&lname=Ford",true);xhr.send();
POST request

The POST request needs to add a request header to let the background know the format of the parameters we requested so that the background can parse our data. In addition, the transmitted data needs to be formatted into the Send method.

var xhr = new XMLHttpRequest();xhr.open("POST","/try/ajax/demo_post2.php",true);xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");xhr.send("fname=Henry&lname=Ford");
Accept data and process data

XMLHttpRequest related properties and events for an object

Properties Description
Status $: "OK"
ResponseText Gets the response data in the form of a string.
Responsexml Get the response data in XML form.
ReadyState The state of being xmlhttprequest. When a request is sent to the background, the status changes from 0 to 4.
0: Request not initialized
1: Server Connection established
2: Request received
3: In Request processing
4: The request is complete and the response is ready
onReadyStateChange This function is called whenever the ReadyState property is changed.

The developer can help us to judge the result of object request by listening to the onReadyStateChange event of XMLHttpRequest object and judging the state of readystate in the callback function of the event.

Full instance
    • A complete GET request example
// get请求var xhr = new XMLHttpRequest();xhr.open(‘GET‘, ‘/api/user?id=333‘, true);xhr.send();xhr.onreadystatechange = function (e) { if (xhr.readyState == 4 && xhr.status == 200) { console.log(xhr.responseText); }};
    • Complete POST Request example
var xhr = new XMLHttpRequest();xhr.open(‘POST‘, ‘/api/user‘, true);// POST请求需要设置此参数xhr.setRequestHeader(‘Content-type‘, ‘application/x-www-form-urlencoded‘)xhr.send(‘name=33&ks=334‘);xhr.onreadystatechange = function (e) { if (xhr.readyState == 4 && xhr.status == 200) { console.log(xhr.responseText); }};
Encapsulating native AJAX Requests

Encapsulating a GET request

/** * Ajax Get Request Helper method *@param {String} URL request background address *After the @param {Function} callback is requested, the data returned is successful, and this method is called, which takes a parameter that is the data returned in the background. * @return undefined */function Span class= "Hljs-title" >ajaxget (URL, callback) {var xhr = new XMLHttpRequest (); Xhr.open ( ' GET ', url, true); Xhr.send (); Xhr.onreadystatechange = function  () {if (xhr.readystate = 4 & & xhr.status = = 200) {callback (Xhr.responsetext);}}} //call Ajaxget ( '/user.json ', < Span class= "Hljs-keyword" >function     

Encapsulating a POST request

functionAjaxpost (URL, data, callback) {var xhr =New XMLHttpRequest (); Xhr.open (' POST ', url,true); Xhr.setrequestheader (' Content-type ', application/x-www-form-urlencoded '); Xhr.send (data); Xhr.onreadystatechange = function ( if (xhr.readystate = 4 & & xhr.status = = 200) {callback (Xhr.responsetext);}}} //call Ajaxpost ( '/api/user ',  ' id=9 &com=aicoder ', function ( Data) {//back in the background is the string type. To turn it into JSON, you must manually convert it yourself. var user = json.parse (data); console.log (user.id); console.log (user.com);          

Native Ajax Request Tutorial

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.