针对获取到location.href的兼容代码:javascript
- try {
- ajaxLocation = location.href;
- } catch( e ) {
-
-
- ajaxLocation = document.createElement( "a" );
- ajaxLocation.href = "";
- ajaxLocation = ajaxLocation.href;
- }
note:若是经过location.href获取地址出错,那么咱们就经过建立A标签,而后获取该标签的href!在IE中能够打印主机名,如"http://locahost:8080/"
关于去除URL中的hash值,同时兼容IE7,若是没有协议字段咱们要手动添加:php
- var ajaxLocation="http://localhost:8080/qinl/a.action?#23"
- var rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/;
- var rhash = /#.*$/;
- var rprotocol = /^\/\
- var ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
- var result=ajaxLocation.replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
匹配是否跨域请求的部分:html
- var rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/;
- alert(rurl.exec("http://localhost:8080/qinl/xx.action"));
- var ajaxLocation=location.href;
- var ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
- alert(ajaxLocParts);
首先来一段精简版的$.ajax方法:也就是其中的原理java
- var completeDeferred = jQuery.Callbacks("once memory");
- var dfd=new $.Deferred();
- var jqXHR={
- }
- dfd.promise(jqXHR).complete=completeDeferred.add;
- var f1=function()
- {
- alert("f1");
- }
- jqXHR.done(f1).complete(f1);
- completeDeferred.fire();
- dfd.resolve();
ajax源码分析:node
- ajax: function( url, options ) {
-
-
- if ( typeof url === "object" ) {
- options = url;
- url = undefined;
- }
-
-
- options = options || {};
- var
- parts,
-
- i,
-
- cacheURL,
-
- responseHeadersString,
-
- timeoutTimer,
-
- fireGlobals,
- transport,
-
- responseHeaders,
-
- s = jQuery.ajaxSetup( {}, options ),
-
-
- callbackContext = s.context || s,
-
-
-
- globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ?
- jQuery( callbackContext ) :
- jQuery.event,
-
-
- deferred = jQuery.Deferred(),
-
- completeDeferred = jQuery.Callbacks("once memory"),
-
-
- statusCode = s.statusCode || {},
-
- requestHeaders = {},
- requestHeadersNames = {},
-
- state = 0,
-
- strAbort = "canceled",
-
-
-
- jqXHR = {
- readyState: 0,
-
- getResponseHeader: function( key ) {
- var match;
-
- if ( state === 2 ) {
- if ( !responseHeaders ) {
- responseHeaders = {};
-
-
- while ( (match = rheaders.exec( responseHeadersString )) ) {
- responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
- }
- }
-
- match = responseHeaders[ key.toLowerCase() ];
- }
- return match == null ? null : match;
- },
-
-
-
- getAllResponseHeaders: function() {
- return state === 2 ? responseHeadersString : null;
- },
-
-
-
- setRequestHeader: function( name, value ) {
- var lname = name.toLowerCase();
-
- if ( !state ) {
- name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
- requestHeaders[ name ] = value;
- }
- return this;
- },
-
-
-
- overrideMimeType: function( type ) {
- if ( !state ) {
- s.mimeType = type;
- }
- return this;
- },
-
-
- statusCode: function( map ) {
- var code;
- if ( map ) {
- if ( state < 2 ) {
- for ( code in map ) {
-
- statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
- }
- } else {
-
- jqXHR.always( map[ jqXHR.status ] );
- }
- }
- return this;
- },
-
-
-
- abort: function( statusText ) {
- var finalText = statusText || strAbort;
- if ( transport ) {
- transport.abort( finalText );
- }
- done( 0, finalText );
- return this;
- }
- };
-
-
-
-
-
-
- deferred.promise( jqXHR ).complete = completeDeferred.add;
-
- jqXHR.success = jqXHR.done;
-
-
- jqXHR.error = jqXHR.fail;
-
-
-
-
-
- s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
-
-
-
- s.type = options.method || options.type || s.method || s.type;
-
-
-
- s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ];
-
-
-
- if ( s.crossDomain == null ) {
-
- parts = rurl.exec( s.url.toLowerCase() );
-
-
- s.crossDomain = !!( parts &&
- ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
- ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !==
- ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) )
- );
- }
-
-
-
- if ( s.data && s.processData && typeof s.data !== "string" ) {
- s.data = jQuery.param( s.data, s.traditional );
- }
-
-
- inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
-
-
-
- if ( state === 2 ) {
- return jqXHR;
- }
-
-
-
-
- fireGlobals = jQuery.event && s.global;
-
- if ( fireGlobals && jQuery.active++ === 0 ) {
- jQuery.event.trigger("ajaxStart");
- }
-
-
-
- s.type = s.type.toUpperCase();
-
-
-
-
- s.hasContent = !rnoContent.test( s.type );
-
-
-
-
- cacheURL = s.url;
-
-
-
- if ( !s.hasContent ) {
-
-
- if ( s.data ) {
-
-
-
- cacheURL = ( s.url += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data );
-
- delete s.data;
- }
-
-
-
- if ( s.cache === false ) {
-
-
- s.url = rts.test( cacheURL ) ?
-
-
-
- cacheURL.replace( rts, "$1_=" + nonce++ ) :
-
-
- cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++;
- }
- }
-
-
-
-
- if ( s.ifModified ) {
-
-
- if ( jQuery.lastModified[ cacheURL ] ) {
- jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
- }
-
-
- if ( jQuery.etag[ cacheURL ] ) {
- jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
- }
- }
-
-
-
-
- if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
- jqXHR.setRequestHeader( "Content-Type", s.contentType );
- }
-
-
-
-
- jqXHR.setRequestHeader(
- "Accept",
- s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
-
-
-
-
-
-
-
-
- s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
- s.accepts[ "*" ]
- );
-
-
- for ( i in s.headers ) {
- jqXHR.setRequestHeader( i, s.headers[ i ] );
- }
-
-
-
-
-
- if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
-
- return jqXHR.abort();
- }
-
- strAbort = "abort";
-
-
-
-
- for ( i in { success: 1, error: 1, complete: 1 } ) {
- jqXHR[ i ]( s[ i ] );
- }
-
-
-
- transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
-
- if ( !transport ) {
- done( -1, "No Transport" );
- } else {
-
-
- jqXHR.readyState = 1;
-
-
-
-
- if ( fireGlobals ) {
- globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
- }
-
-
-
- if ( s.async && s.timeout > 0 ) {
- timeoutTimer = setTimeout(function() {
- jqXHR.abort("timeout");
- }, s.timeout );
- }
-
- try {
- state = 1;
- transport.send( requestHeaders, done );
- } catch ( e ) {
-
- if ( state < 2 ) {
- done( -1, e );
-
- } else {
- throw e;
- }
- }
- }
总结:jquery
(1)调用 jQuery.ajaxSetup( {}, options )让最终options具备jQuery内置的全部的属性,同时也包括用户调用ajax方法的时候传入的全部的属性和方法!
(2)建立jqXHR对象,让该对象具备Deferred的全部属性和方法,该Deferred对象能够绑定用户的success和error方法。可是用户传入的compelte方法表示任何状况下都会调用,咱们就引入了一个Callbacks对象,把complete回调函数存入该Callback中(用fireWith调用)ajax
(3)对URL处理,取出hash加上协议名称,为type赋值,也就是Get/Post方法(用户能够经过method或者type传入该方法);指定dataTypes说明用户须要要的数据类型(用户经过dataType传入);若是用户没有明确指定crossDomain,那么本身判断,若是用户传入的URL也就是访问的URL和当前的location.href不相同(包括协议名称,主机名,端口号等),那么直接把crossDomain设置为true;若是传入了数据,也就是data那么经过 jQuery.param方法把这个数据序列化;跨域
(4)上述步骤完成之后,咱们就调用inspectPrefiltersOrTransports,这个方法传入了prefilters,表示对prefilters中全部的预处理函数进行检测,该方法能够修改前面全部的参数,固然也能够添加新的信息!(这里是prefilters)数组
(5)若是用户传入了global参数,那么咱们在这个步骤执行"ajaxStart"事件promise
globalBoolean类型
默认值:true
。指示是否触发全局Ajax事件。将该值设为false
将阻止全局事件处理函数被触发,例如ajaxStart()和ajaxStop()。它能够用来控制各类Ajax事件。
(6)若是指定了get/head请求,那么若是有数据那么把数据绑定到URL后面(同时保存这个URL以便缓存URL)。同时若是是指定了get/head时候还明确指定了不能缓存数据,那么咱们把缓存的URL后面添加一个随机数,随机数是当前时间!(一开始设定了缓存URL是用户传入的ur,get/head请求等都会对URL修改)
(7)若是用户指定了ifModified,表示只有数据改变时候才发送请求。若是这个URL已经访问过了,那么咱们取出访问该URL时候服务器给的etag和if-none-match标签,而且把他们经过"If-None-Match和If-Modified-Since形式发送给服务器端,让服务器端去判断数据有没有改变。这两个头是在done方法中,也就是成功回调时候设置的!
ifModifiedBoolean类型
默认值:false
。容许当前请求仅在服务器数据改变时获取新数据(如未更改,浏览器从缓存中获取数据)。它使用HTTP头信息Last-Modified
来判断。从jQuery 1.4开始,他也会检查服务器指定的'etag'来肯定数据是否已被修改。
(8)设置数据类型content-type,把content-type的头添加到jqXHR对象上
contentTypeString类型
默认值:'application/x-www-form-urlencoded; charset=UTF-8'。使用指定的内容编码类型将数据发送给服务器。W3C的XMLHttpRequest规范规定charset始终是UTF-8,你若是将其改成其余字符集,也没法强制浏览器改字符编码。
(9)设置accept头,告诉服务器浏览器可以接受的数据类型
acceptsObject类型
默认值:取决于dataType
属性。发送的内容类型请求头,用于告诉服务器——浏览器能够接收服务器返回何种类型的响应。若是传入的是"*"结果就是"*/*",不然就是如格式"text/html,*/*;q=0.01"
(10)设置用户经过headers传入的HTTP头
headersObject类型1.5 新增
默认值:{}
。以对象形式指定附加的请求头信息。请求头X-Requested-With: XMLHttpRequest
将始终被添加,固然你也能够在此处修改默认的XMLHttpRequest值。headers
中的值能够覆盖beforeSend
回调函数中设置的请求头(意即beforeSend先被调用)。
(11)调用beforeSend
beforeSendFunction类型
指定在请求发送前须要执行的回调函数。该函数还有两个参数:其一是jqXHR
对象,其二是当前settings
对象。这是一个Ajax事件,若是该函数返回false
,将取消本次ajax请求。
(12)这一步才把咱们传入的success,error,compelete放入相应的Deferred对象和Callback对象里面,以备回调!
(13)这一步是重点:调用transport里面全部的函数集合。函数调用的返回结果是一个对象,该对象有send和abort方法。调用send方法就是真正的向服务器发送数据,若是没有获得transport对象那么表示请求失败。若是获得了这个对象,那么咱们把readyState设置为1,而后调用send方法,可是调用send方法以前咱们要调用ajaxSend方法!在send方法调用时候transport.send( requestHeaders, done );咱们传入了回调函数done方法,该方法处理了回调的逻辑!
咱们看看下面的done方法的处理逻辑:
- function done( status, nativeStatusText, responses, headers ) {
- var isSuccess, success, error, response, modified,
- statusText = nativeStatusText;
-
-
- if ( state === 2 ) {
- return;
- }
-
-
- state = 2;
-
-
- if ( timeoutTimer ) {
- clearTimeout( timeoutTimer );
- }
-
-
- transport = undefined;
-
-
- responseHeadersString = headers || "";
-
-
- jqXHR.readyState = status > 0 ? 4 : 0;
-
-
- isSuccess = status >= 200 && status < 300 || status === 304;
-
-
- if ( responses ) {
- response = ajaxHandleResponses( s, jqXHR, responses );
- }
-
- response = ajaxConvert( s, response, jqXHR, isSuccess );
-
- if ( isSuccess ) {
-
-
- if ( s.ifModified ) {
- modified = jqXHR.getResponseHeader("Last-Modified");
- if ( modified ) {
- jQuery.lastModified[ cacheURL ] = modified;
- }
-
- modified = jqXHR.getResponseHeader("etag");
- if ( modified ) {
- jQuery.etag[ cacheURL ] = modified;
- }
- }
-
-
- if ( status === 204 || s.type === "HEAD" ) {
- statusText = "nocontent";
-
-
- } else if ( status === 304 ) {
- statusText = "notmodified";
-
-
- } else {
- statusText = response.state;
- success = response.data;
- error = response.error;
- isSuccess = !error;
- }
- } else {
-
-
-
- error = statusText;
- if ( status || !statusText ) {
- statusText = "error";
- if ( status < 0 ) {
- status = 0;
- }
- }
- }
-
-
- jqXHR.status = status;
- jqXHR.statusText = ( nativeStatusText || statusText ) + "";
-
- if ( isSuccess ) {
-
-
- deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
- } else {
- deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
- }
-
- jqXHR.statusCode( statusCode );
- statusCode = undefined;
-
- if ( fireGlobals ) {
- globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
- [ jqXHR, s, isSuccess ? success : error ] );
- }
-
-
-
- completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
- if ( fireGlobals ) {
-
- globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
-
-
- if ( !( --jQuery.active ) ) {
- jQuery.event.trigger("ajaxStop");
- }
- }
- }
-
- return jqXHR;
- }
- );
note:
(1)state在send调用以前为1,在done方法调用的时候设置为2,默认为0.因此2表示已经回调成功了,1表示send方法已经调用可是尚未回调。
(2)调用顺序是ajaxStart,ajaxSend,ajaxSuccess/ajaxError,ajaxComplete,ajaxStop这就是全局事件的调用顺序!
(3)在done方法中经过resolveWith,rejectWith来触发success,error事件,经过fireWith来触发compelete事件
(4)返回真实的服务器端数据,如responseText服务器端的数据!ajaxHandleResponses做用:把服务器端返回的数据封装到jqXHR对象上面,造成jqXHR["responseText"]=xhr.responseText这种类型!同时把responses中的相应的数据取出来。由于responses={"text":xhr.responseText}是这种类型,这个方法最后造成的返回数据为responses["text"]=xhr.responseText,也就是获得服务器端的数据!
(5)ajaxConverter做用:左后返回一个对象,该对象有state和data属性,如{state:"success",data:response}其中response就是上面提到的通过处理的服务器端返回的数据!
(6)若是指定了global表示支持全局事件的调用,那么在jQuery.active的值为0的时候调用一次ajaxStart,调用完成之后让active自增,在调用ajaxStop以前首先让active自减,若是是0才会调用ajaxStop!