Zepto Source Code Analysis------AJAX Chapter

Source: Internet
Author: User

The superior has studied the Zepto event, also said the Zepto main module constitution. Well, today's talk about how Zepto Ajax is implemented.

OK, same as last time, the code first.

$.ajax =function(options) {//Overwrite Configuration    varSettings = $.extend ({}, Options | | {}),      //not found in whereDeferred = $. Deferred && $. Deferred (), Urlanchor//Complete the configuration overlay     for(Keyinch$.ajaxsettings)if(Settings[key] = = = undefined) Settings[key] =$.ajaxsettings[key]//this involves three function Ajaxstart>triggerglobal>triggerandreturn (triggering Ajax)Ajaxstart (Settings)//is a cross-domain    if(!settings.crossdomain) {Urlanchor= Document.createelement (' A ') Urlanchor.href=Settings.url urlanchor.href=Urlanchor.href//Verify that the cross-domain is true----ensure that the parameters are correctedSettings.crossdomain = (Originanchor.protocol + '//' + originanchor.host)!== (Urlanchor.protocol + '//' +urlanchor.host)}if(!settings.url) Settings.url =window.location.toString ()//Serialization of Dataserializedata (Settings)varDataType =Settings.datatype,//Resolve address If there is a callback then Hasplaceholder = TrueHasplaceholder =/\?. +=\?/. Test (Settings.url)if(hasplaceholder) DataType = ' Jsonp 'if(Settings.cache = = =false|| (        (!options | | Options.cache!==true) &&        (' script ' = = DataType | | ' Jsonp ' = =DataType)))  //Add a selector (not very clear)Settings.url = Appendquery (Settings.url, ' _= ' +Date.now ())if(' jsonp ' = =DataType) {      if(!hasplaceholder) Settings.url=appendquery (Settings.url, Settings.jsonp? (Settings.jsonp + ' =? ') : Settings.jsonp = = =false? "': ' callback=? ')      //Cross-domain with JSONP if it is cross-domain      return$.ajaxjsonp (settings, deferred)}varMIME =Settings.accepts[datatype], headers={}, SetHeader=function(name, value) {headers[name.tolowercase ()]=[Name, value]}, protocol=/^ ([\w-]+:) \/\//.test (settings.url)? Regexp.$1: Window.location.protocol, XHR=settings.xhr (), Nativesetheader=Xhr.setrequestheader, Aborttimeoutif(deferred) deferred.promise (XHR)//if it is a cross-domain request    if(!settings.crossdomain) SetHeader (' X-requested-with ', ' XMLHttpRequest ') SetHeader (' Accept ', MIME | | ‘*/*‘)    if(MIME = Settings.mimetype | |MIME) {      if(Mime.indexof (', ') >-1) MIME = Mime.split (', ', 2) [0] Xhr.overridemimetype&&Xhr.overridemimetype (MIME)}if(Settings.contenttype | | (Settings.contenttype!==false&& settings.data && settings.type.toUpperCase ()! = ' GET ')) SetHeader (' Content-type ', Settings.contenttype | | ' Application/x-www-form-urlencoded ')    if(settings.headers) for(Nameinchsettings.headers) SetHeader (name, Settings.headers[name]) Xhr.setrequestheader=SetHeader//Monitoring Request StatusXhr.onreadystatechange =function() {      if(Xhr.readystate = = 4) {Xhr.onreadystatechange=empty cleartimeout (aborttimeout)varresult, error =false        if((Xhr.status >= && xhr.status <) | | xhr.status = = 304 | | (Xhr.status = = 0 && protocol = = ' File: ') ) {DataType= DataType | | Mimetodatatype (Settings.mimetype | | xhr.getresponseheader (' content-type ')) ) Result=Xhr.responsetextTry {            //http://perfectionkills.com/global-eval-what-are-the-options/            if(DataType = = ' script ') (1, eval) (Result)Else if(DataType = = ' xml ') result =Xhr.responsexmlElse if(DataType = = ' json ') result = Blankre.test (result)?NULL: $.parsejson (Result)}Catch(e) {error=e}if(Error) Ajaxerror (Error, ' ParserError '), XHR, Settings, deferred)Elseajaxsuccess (result, xhr, settings, deferred)}Else{ajaxerror (Xhr.statustext||NULL, Xhr.status? ' ERROR ': ' Abort ', XHR, Settings, deferred)} }    }    if(Ajaxbeforesend (xhr, settings) = = =false) {Xhr.abort () Ajaxerror (NULL, ' Abort ', XHR, Settings, deferred)returnXHR}if(Settings.xhrfields) for(NameinchSettings.xhrfields) Xhr[name] =Settings.xhrfields[name]//setting up asynchronous and synchronous    varAsync = ' Async 'inchSettings? Settings.async:trueXhr.open (Settings.type, Settings.url, async, Settings.username, Settings.password) for(Nameinchheaders) nativesetheader.apply (XHR, Headers[name])if(Settings.timeout > 0) aborttimeout = setTimeout (function() {Xhr.onreadystatechange=empty Xhr.abort () Ajaxerror (NULL, ' timeout ', XHR, Settings, deferred)}, Settings.timeout)//Avoid sending empty string (#319)Xhr.send (settings.data? Settings.data:NULL)    returnXHR}

OK, this is the core of Ajax, the main comment I read and write on it. In fact, we all know one thing. Whether the post or get must have open (XXX) This method, then we are obviously in the above source code only read a sentence. That's the problem. What do the authors write so much? Let's analyze it from top to bottom. Ajax functions within this function implementation process setting (configuration overrides have already written some configuration in the $.ajaxsettings, extend the user's configuration by extending it in the way)---- Processing is not cross-domain----The request starts---State listens----callback processing-----data parsing. Well, that's the way it goes. The rest of the functions are on their own.

Not only do we use AJAX when we develop the page, we sometimes encounter cross-domain things. OK, let's say how it's implemented across domains. Or on the code, but this time is relatively simple, hey.

$.ajaxjsonp =function(options, deferred) {if(! (' type 'inchOptions))return$.ajax (Options)var_callbackname =Options.jsonpcallback, Callbackname= ($.isfunction (_callbackname)?_callbackname (): _callbackname)|| (' Jsonp ' + (+ +)jsonpid)), script= document.createelement (' script '), Originalcallback=Window[callbackname], responsedata, abort=function(ErrorType) {$ (script). Triggerhandler (' Error ', ErrorType | | ' Abort ')}, XHR={abort:abort}, Aborttimeoutif(deferred) deferred.promise (XHR) $ (script). On (' Load error ',function(E, ErrorType) {cleartimeout (aborttimeout) $ (script). Off (). Remove ()if(E.type = = ' ERROR ' | |!responsedata) {Ajaxerror (NULL, ErrorType | | ' Error ', XHR, Options, deferred)} Else{ajaxsuccess (responsedata[0], XHR, Options, deferred)} Window[callbackname]=Originalcallbackif(ResponseData &&$.isfunction (Originalcallback)) Originalcallback (responsedata[0]) Originalcallback= ResponseData =undefined}) if(Ajaxbeforesend (XHR, options) = = =false) {Abort (' Abort ')      returnXHR} Window[callbackname]=function() {ResponseData=arguments} script.src= Options.url.replace (/\) (. +) =\?/, '? $1= ' +callbackname) document.head.appendChild (script)if(Options.timeout > 0) aborttimeout = setTimeout (function() {Abort (' Timeout ')}, Options.timeout)returnXHR}

I didn't even write a note. Obviously, this is very simple. Right. Let's talk about the principle of implementation.

In general, cross-domain is subject to the same-origin policy, which is what we call cross-domain. So what can we do to get rid of this limitation. Well, usually we often do so or <script src= "" ><script/> we will find that even if these images are Baidu we can also get over, (but now Baidu seems to be not, Some pictures, hehe). We can think of. JSON yes, not the same as JS. Then we can directly quote a JS and then get the content out of it.

The general approach is this. Reference a JS, and then add to the head, here you need to write the name of the callback function in the path of JS. And then the data is like a pass-back. But there's a problem here. We saw that there was such a word window[callback]. In other words, the callback function must be mounted under the Window object, otherwise it will not work.

I'll continue the form ... Hey.

Zepto Source Code Analysis------AJAX Chapter

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.