Simple implementation of jquery-style Ajax

Source: Internet
Author: User
Tags dataquest

Ajax is already a very old topic. Now all kinds of frameworks have mature encapsulation, so that developers can skillfully Create Ajax-based applications at a low learning cost.

The disadvantages here are also obvious. A considerable number of developers have little knowledge about the underlying Ajax layer. If they leave the framework, they may be overwhelmed ----

Of course, this situation generally does not occur in the development process, but more often occurs in the interview process ~ Everyone knows.

We recommend you refer to the w3cschool Ajax tutorial, which is simple, basic, and practical.

What we need to achieve today is to imitate the jquery-style Ajax call method:

 
$. Get (URL, [data], [callback]); $. Post (URL, [data], [callback]);

The final goal is to initiate an asynchronous request like this and process the returned data:

 
Ajax. get ('get. PHP ', {FOO: 'bar'}, function (data) {onget (data) ;}); Ajax. post ('Post. PHP ', {pre: 'huvtx', last: 'zhongwen Chinese ##@ teshuf '}, function (data) {onpost (data );});

First, think about it.CodeAfter thinking about how to organize:

VaR Ajax = Ajax | {}; Ajax = (function () {// If jquery Ajax is available, use jquery directly. ajax if (window. jquery & jquery. ajax) return jquery. ajax;/** No. You still need to use the familiar Singleton mode to configure Ajax objects. * xhrs is used to store the xhr objects created by each call, xhr does not need to be reused */var it ={}, win = Window, Doc = Document, xhrs ={}; it. createxhr = function () {/** generate an XMLHTTPRequest object * return xhr; */}; it. getxhr = function (t) {/** generate an xhr object based on the call time to coexist in xhrs. * call it. createxhr * return xhrs [T]; */}; it. dataquest = function (data) {/** converts a data object to a string * {FOO: bar, foo2: bar2 }=> Foo = Bar & foo2 = bar2 * If the input string is left unchanged * return string; */}; it. mixurl = function (URL, query) {/** link the URL to Quest * return URL; */}; it. request = function (method, URL, Data, callback, async) {/** create an xhr and send a request * method string [get] | [Post] * URL string * data string | object * callback function * async true | false true is asynchronous * // ** the following steps cannot be remembered: * createxhr open onreadystatechange send */var xhr = it. getxhr (t); xhr. open (method, URL, Syn); xhr. onreadystatechange = function (e ){}; /** if a value is required for post-based sentdata * if you want to submit a form, you need to set the requestheader as follows * If the get-based sentdata method is used, or null */If (Method = 'post') {sentdata = quest; xhr. setRequestHeader ('content-type', 'application/X-WWW-form-urlencoded');}; xhr. send (sentdata) ;};/** get method to call the Request Method */it. get = function (URL, Data, callback, async) {It. request ('get', URL, Data, callback, async) ;};/** POST method Implementation call Request Method */it. post = function (URL, Data, callback, async) {It. request ('post', URL, Data, callback, async) ;};/** clear the used xhr object */it. clearxhr = function (t) {If (xhrs [T]) {xhrs [T]. onreadystatuschange = NULL; xhrs [T] = NULL ;}};/** simple trim is used to process responsetext */it. trim = function (s) {return S. replace (/(^ \ s *) | (\ s * $)/g, '') ;};/** return Ajax object */return it after configuration is complete ;}) ();

complete code:

VaR Ajax = Ajax | |{}; Ajax = (function () {var it ={}, win = Window, Doc = Document, xhrs ={}; it. createxhr = function () {var xhr = NULL; If (win. XMLHttpRequest) {try {xhr = new XMLHttpRequest ()} catch (e) {xhr = NULL ;}} else {try {xhr = new activexobject ('msxml2. XMLHTTP ');} catch (e) {try {xhr = new activexobject ('Microsoft. XMLHTTP ');} catch (e) {xhr = NULL ;}} return xhr ;}; it. getxhr = function (t) {If (xhrs [T]) retur N xhrs [T]; xhrs [T] = it. createxhr (); Return xhrs [T];}; it. dataquest = function (data) {var quest = ''; If (typeof DATA = 'string') {quest = data;} else if (typeof DATA = 'object ') {var parms = []; for (VAR o in data) {parms. push (O + '=' + encodeuricomponent (data [O]) ;}; quest = parms. join ('&') ;}; return quest ;}; it. mixurl = function (URL, query) {URL + = URL. indexof ('? ')> 0? '&':'? '; Url + = query; return URL. Replace (/(\?) +/G ,'? '). Replace (/(\ &) +/g, '&') ;}; it. request = function (method, URL, Data, callback, async) {var T = new date () * 1, xhr = it. getxhr (t), sentdata = NULL, quest = it. dataquest (data), SYN = (typeof async = 'undefined ')? True: async; If (Method = 'get') {url = it. mixurl (URL, Quest) ;}; xhr. open (method, URL, Syn); xhr. onreadystatechange = function (e) {// alert (xhr. status); If (xhr. readystate = 4) {If (xhr. status >=200 & xhr. status <400) {var DATA = it. trim (xhr. responsetext); If (Data & typeof callback = 'function') {callback (data); setTimeout (function () {It. clearxhr (xhr) ;}, 0) ;}}}; if (Method = 'post') {sentdata = quest; xhr. setRequestHeader ('content-type', 'application/X-WWW-form-urlencoded');}; xhr. send (sentdata) ;}; it. get = function (URL, Data, callback, async) {It. request ('get', URL, Data, callback, async) ;}; it. post = function (URL, Data, callback, async) {It. request ('post', URL, Data, callback, async) ;}; it. clearxhr = function (t) {If (xhrs [T]) {xhrs [T]. onreadystatuschange = NULL; xhrs [T] = NULL ;}}; it. trim = function (s) {return S. replace (/(^ \ s *) | (\ s * $)/g, '') ;}; return it ;})();

Call method:

 
<! Doctype HTML>  

Check what the server has done:

 
/** Get. php is too simple */<? PHP $ Foo = $ _ Get ['foo']; echo 'your foo is ~ '. $ Foo;?> /** Post. php is simpler ~ */<? PHP $ pre =$ _ post ['pre']; $ last =$ _ post ['last']; echo $ pre. $ last;?>

End ~

Finally, I would like to add some relatedArticle:

Differences between get and post

Http://www.nowamagic.net/librarys/veda/detail/1919

The real difference between get and post is no longer transmitted using uploads.

 Most answers on the Internet are incorrect.

Http://www.yining.org/2010/05/04/http-get-vs-post-and-thoughts/

# Differences between http get and post

 

 

 

Related Article

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.