The encapsulation of the AJAX request get method

Source: Internet
Author: User
Tags define get

function get (URL, options, callback) { //define Get function

if (XMLHttpRequest) {

var xhr=new xmlhttprequest ();

}else{

var xhr=new activexobject ("Microsoft.XMLHTTP"); //compatible with IE

}


xhr. onreadystatechange = function (callback) {

if (xhr. readyState = = = 4) {

if ((Xhr.status >= && xhr.status <) | | xhr.status = = 304) {

Callback (Xhr.responsetext);

}else{

Alert ("The request was unsuccessful:" + XHR. Status)

}

}

}

var seriurl = url + '? ' + serialize (options);

XHR. Open (' Get ', Seriurl, true);

XHR. Send (NULL);
}


function serialize (data) {

if (!data) return ';

var pairs = [], value;

for (name in data) { //Traversal Object Properties

if (!data.hasownproperty (name)) continue; //Filter out properties and methods of inherited prototypes

if (typeof data[name] = = = ' function ') continue; //Filter out function method

Value = Data[name].tostring (); //attribute value to string

Name = encodeURIComponent (name); //The property name string can be encoded as a URI component. Returns a copy of the value uristring, where some of the characters are replaced by a hexadecimal escape sequence.

Value = encodeURIComponent (value); //property value for URI encoding.

Pairs.push (name + ' = ' + value); //property names and values into an array

}

Return Pairs.join (' & '); //The elements in the array are returned in string form with & separate

}


Get ('/information ', {name: ' NetEase ', age:18}, function (data) {

Console.log (data);

  Processing return Data

});

The encapsulation of the AJAX request get method

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.