Blame | Last modification | View Log | RSS feed
define(["./core","./var/rnotwhite","./ajax/var/nonce","./ajax/var/rquery","./core/init","./ajax/parseJSON","./ajax/parseXML","./deferred"], function( jQuery, rnotwhite, nonce, rquery ) {varrhash = /#.*$/,rts = /([?&])_=[^&]*/,rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg,// #7653, #8125, #8152: local protocol detectionrlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,rnoContent = /^(?:GET|HEAD)$/,rprotocol = /^\/\//,rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,/* Prefilters* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)* 2) These are called:* - BEFORE asking for a transport* - AFTER param serialization (s.data is a string if s.processData is true)* 3) key is the dataType* 4) the catchall symbol "*" can be used* 5) execution will start with transport dataType and THEN continue down to "*" if needed*/prefilters = {},/* Transports bindings* 1) key is the dataType* 2) the catchall symbol "*" can be used* 3) selection will start with transport dataType and THEN go to "*" if needed*/transports = {},// Avoid comment-prolog char sequence (#10098); must appease lint and evade compressionallTypes = "*/".concat( "*" ),// Document locationajaxLocation = window.location.href,// Segment location into partsajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransportfunction addToPrefiltersOrTransports( structure ) {// dataTypeExpression is optional and defaults to "*"return function( dataTypeExpression, func ) {if ( typeof dataTypeExpression !== "string" ) {func = dataTypeExpression;dataTypeExpression = "*";}var dataType,i = 0,dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || [];if ( jQuery.isFunction( func ) ) {// For each dataType in the dataTypeExpressionwhile ( (dataType = dataTypes[i++]) ) {// Prepend if requestedif ( dataType[0] === "+" ) {dataType = dataType.slice( 1 ) || "*";(structure[ dataType ] = structure[ dataType ] || []).unshift( func );// Otherwise append} else {(structure[ dataType ] = structure[ dataType ] || []).push( func );}}}};}// Base inspection function for prefilters and transportsfunction inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {var inspected = {},seekingTransport = ( structure === transports );function inspect( dataType ) {var selected;inspected[ dataType ] = true;jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) {options.dataTypes.unshift( dataTypeOrTransport );inspect( dataTypeOrTransport );return false;} else if ( seekingTransport ) {return !( selected = dataTypeOrTransport );}});return selected;}return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );}// A special extend for ajax options// that takes "flat" options (not to be deep extended)// Fixes #9887function ajaxExtend( target, src ) {var key, deep,flatOptions = jQuery.ajaxSettings.flatOptions || {};for ( key in src ) {if ( src[ key ] !== undefined ) {( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ];}}if ( deep ) {jQuery.extend( true, target, deep );}return target;}/* Handles responses to an ajax request:* - finds the right dataType (mediates between content-type and expected dataType)* - returns the corresponding response*/function ajaxHandleResponses( s, jqXHR, responses ) {var ct, type, finalDataType, firstDataType,contents = s.contents,dataTypes = s.dataTypes;// Remove auto dataType and get content-type in the processwhile ( dataTypes[ 0 ] === "*" ) {dataTypes.shift();if ( ct === undefined ) {ct = s.mimeType || jqXHR.getResponseHeader("Content-Type");}}// Check if we're dealing with a known content-typeif ( ct ) {for ( type in contents ) {if ( contents[ type ] && contents[ type ].test( ct ) ) {dataTypes.unshift( type );break;}}}// Check to see if we have a response for the expected dataTypeif ( dataTypes[ 0 ] in responses ) {finalDataType = dataTypes[ 0 ];} else {// Try convertible dataTypesfor ( type in responses ) {if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {finalDataType = type;break;}if ( !firstDataType ) {firstDataType = type;}}// Or just use first onefinalDataType = finalDataType || firstDataType;}// If we found a dataType// We add the dataType to the list if needed// and return the corresponding responseif ( finalDataType ) {if ( finalDataType !== dataTypes[ 0 ] ) {dataTypes.unshift( finalDataType );}return responses[ finalDataType ];}}/* Chain conversions given the request and the original response* Also sets the responseXXX fields on the jqXHR instance*/function ajaxConvert( s, response, jqXHR, isSuccess ) {var conv2, current, conv, tmp, prev,converters = {},// Work with a copy of dataTypes in case we need to modify it for conversiondataTypes = s.dataTypes.slice();// Create converters map with lowercased keysif ( dataTypes[ 1 ] ) {for ( conv in s.converters ) {converters[ conv.toLowerCase() ] = s.converters[ conv ];}}current = dataTypes.shift();// Convert to each sequential dataTypewhile ( current ) {if ( s.responseFields[ current ] ) {jqXHR[ s.responseFields[ current ] ] = response;}// Apply the dataFilter if providedif ( !prev && isSuccess && s.dataFilter ) {response = s.dataFilter( response, s.dataType );}prev = current;current = dataTypes.shift();if ( current ) {// There's only work to do if current dataType is non-autoif ( current === "*" ) {current = prev;// Convert response if prev dataType is non-auto and differs from current} else if ( prev !== "*" && prev !== current ) {// Seek a direct converterconv = converters[ prev + " " + current ] || converters[ "* " + current ];// If none found, seek a pairif ( !conv ) {for ( conv2 in converters ) {// If conv2 outputs currenttmp = conv2.split( " " );if ( tmp[ 1 ] === current ) {// If prev can be converted to accepted inputconv = converters[ prev + " " + tmp[ 0 ] ] ||converters[ "* " + tmp[ 0 ] ];if ( conv ) {// Condense equivalence convertersif ( conv === true ) {conv = converters[ conv2 ];// Otherwise, insert the intermediate dataType} else if ( converters[ conv2 ] !== true ) {current = tmp[ 0 ];dataTypes.unshift( tmp[ 1 ] );}break;}}}}// Apply converter (if not an equivalence)if ( conv !== true ) {// Unless errors are allowed to bubble, catch and return themif ( conv && s[ "throws" ] ) {response = conv( response );} else {try {response = conv( response );} catch ( e ) {return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current };}}}}}}return { state: "success", data: response };}jQuery.extend({// Counter for holding the number of active queriesactive: 0,// Last-Modified header cache for next requestlastModified: {},etag: {},ajaxSettings: {url: ajaxLocation,type: "GET",isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),global: true,processData: true,async: true,contentType: "application/x-www-form-urlencoded; charset=UTF-8",/*timeout: 0,data: null,dataType: null,username: null,password: null,cache: null,throws: false,traditional: false,headers: {},*/accepts: {"*": allTypes,text: "text/plain",html: "text/html",xml: "application/xml, text/xml",json: "application/json, text/javascript"},contents: {xml: /xml/,html: /html/,json: /json/},responseFields: {xml: "responseXML",text: "responseText",json: "responseJSON"},// Data converters// Keys separate source (or catchall "*") and destination types with a single spaceconverters: {// Convert anything to text"* text": String,// Text to html (true = no transformation)"text html": true,// Evaluate text as a json expression"text json": jQuery.parseJSON,// Parse text as xml"text xml": jQuery.parseXML},// For options that shouldn't be deep extended:// you can add your own custom options here if// and when you create one that shouldn't be// deep extended (see ajaxExtend)flatOptions: {url: true,context: true}},// Creates a full fledged settings object into target// with both ajaxSettings and settings fields.// If target is omitted, writes into ajaxSettings.ajaxSetup: function( target, settings ) {return settings ?// Building a settings objectajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :// Extending ajaxSettingsajaxExtend( jQuery.ajaxSettings, target );},ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),ajaxTransport: addToPrefiltersOrTransports( transports ),// Main methodajax: function( url, options ) {// If url is an object, simulate pre-1.5 signatureif ( typeof url === "object" ) {options = url;url = undefined;}// Force options to be an objectoptions = options || {};var transport,// URL without anti-cache paramcacheURL,// Response headersresponseHeadersString,responseHeaders,// timeout handletimeoutTimer,// Cross-domain detection varsparts,// To know if global events are to be dispatchedfireGlobals,// Loop variablei,// Create the final options objects = jQuery.ajaxSetup( {}, options ),// Callbacks contextcallbackContext = s.context || s,// Context for global events is callbackContext if it is a DOM node or jQuery collectionglobalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ?jQuery( callbackContext ) :jQuery.event,// Deferredsdeferred = jQuery.Deferred(),completeDeferred = jQuery.Callbacks("once memory"),// Status-dependent callbacksstatusCode = s.statusCode || {},// Headers (they are sent all at once)requestHeaders = {},requestHeadersNames = {},// The jqXHR statestate = 0,// Default abort messagestrAbort = "canceled",// Fake xhrjqXHR = {readyState: 0,// Builds headers hashtable if neededgetResponseHeader: 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;},// Raw stringgetAllResponseHeaders: function() {return state === 2 ? responseHeadersString : null;},// Caches the headersetRequestHeader: function( name, value ) {var lname = name.toLowerCase();if ( !state ) {name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;requestHeaders[ name ] = value;}return this;},// Overrides response content-type headeroverrideMimeType: function( type ) {if ( !state ) {s.mimeType = type;}return this;},// Status-dependent callbacksstatusCode: function( map ) {var code;if ( map ) {if ( state < 2 ) {for ( code in map ) {// Lazy-add the new callback in a way that preserves old onesstatusCode[ code ] = [ statusCode[ code ], map[ code ] ];}} else {// Execute the appropriate callbacksjqXHR.always( map[ jqXHR.status ] );}}return this;},// Cancel the requestabort: function( statusText ) {var finalText = statusText || strAbort;if ( transport ) {transport.abort( finalText );}done( 0, finalText );return this;}};// Attach deferredsdeferred.promise( jqXHR ).complete = completeDeferred.add;jqXHR.success = jqXHR.done;jqXHR.error = jqXHR.fail;// Remove hash character (#7531: and string promotion)// Add protocol if not provided (prefilters might expect it)// Handle falsy url in the settings object (#10093: consistency with old signature)// We also use the url parameter if availables.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );// Alias method option to type as per ticket #12004s.type = options.method || options.type || s.method || s.type;// Extract dataTypes lists.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ];// A cross-domain request is in order when we have a protocol:host:port mismatchif ( 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" ) ) ));}// Convert data if not already a stringif ( s.data && s.processData && typeof s.data !== "string" ) {s.data = jQuery.param( s.data, s.traditional );}// Apply prefiltersinspectPrefiltersOrTransports( prefilters, s, options, jqXHR );// If request was aborted inside a prefilter, stop thereif ( state === 2 ) {return jqXHR;}// We can fire global events as of now if asked to// Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118)fireGlobals = jQuery.event && s.global;// Watch for a new set of requestsif ( fireGlobals && jQuery.active++ === 0 ) {jQuery.event.trigger("ajaxStart");}// Uppercase the types.type = s.type.toUpperCase();// Determine if request has contents.hasContent = !rnoContent.test( s.type );// Save the URL in case we're toying with the If-Modified-Since// and/or If-None-Match header later oncacheURL = s.url;// More options handling for requests with no contentif ( !s.hasContent ) {// If data is available, append data to urlif ( s.data ) {cacheURL = ( s.url += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data );// #9682: remove data so that it's not used in an eventual retrydelete s.data;}// Add anti-cache in url if neededif ( s.cache === false ) {s.url = rts.test( cacheURL ) ?// If there is already a '_' parameter, set its valuecacheURL.replace( rts, "$1_=" + nonce++ ) :// Otherwise add one to the endcacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++;}}// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.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 ] );}}// Set the correct header, if data is being sentif ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {jqXHR.setRequestHeader( "Content-Type", s.contentType );}// Set the Accepts header for the server, depending on the dataTypejqXHR.setRequestHeader("Accept",s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :s.accepts[ "*" ]);// Check for headers optionfor ( i in s.headers ) {jqXHR.setRequestHeader( i, s.headers[ i ] );}// Allow custom headers/mimetypes and early abortif ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {// Abort if not done already and returnreturn jqXHR.abort();}// Aborting is no longer a cancellationstrAbort = "abort";// Install callbacks on deferredsfor ( i in { success: 1, error: 1, complete: 1 } ) {jqXHR[ i ]( s[ i ] );}// Get transporttransport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );// If no transport, we auto-abortif ( !transport ) {done( -1, "No Transport" );} else {jqXHR.readyState = 1;// Send global eventif ( fireGlobals ) {globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );}// Timeoutif ( s.async && s.timeout > 0 ) {timeoutTimer = setTimeout(function() {jqXHR.abort("timeout");}, s.timeout );}try {state = 1;transport.send( requestHeaders, done );} catch ( e ) {// Propagate exception as error if not doneif ( state < 2 ) {done( -1, e );// Simply rethrow otherwise} else {throw e;}}}// Callback for when everything is donefunction done( status, nativeStatusText, responses, headers ) {var isSuccess, success, error, response, modified,statusText = nativeStatusText;// Called onceif ( state === 2 ) {return;}// State is "done" nowstate = 2;// Clear timeout if it existsif ( timeoutTimer ) {clearTimeout( timeoutTimer );}// Dereference transport for early garbage collection// (no matter how long the jqXHR object will be used)transport = undefined;// Cache response headersresponseHeadersString = headers || "";// Set readyStatejqXHR.readyState = status > 0 ? 4 : 0;// Determine if successfulisSuccess = status >= 200 && status < 300 || status === 304;// Get response dataif ( responses ) {response = ajaxHandleResponses( s, jqXHR, responses );}// Convert no matter what (that way responseXXX fields are always set)response = ajaxConvert( s, response, jqXHR, isSuccess );// If successful, handle type chainingif ( isSuccess ) {// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.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 no contentif ( status === 204 || s.type === "HEAD" ) {statusText = "nocontent";// if not modified} else if ( status === 304 ) {statusText = "notmodified";// If we have data, let's convert it} else {statusText = response.state;success = response.data;error = response.error;isSuccess = !error;}} else {// Extract error from statusText and normalize for non-abortserror = statusText;if ( status || !statusText ) {statusText = "error";if ( status < 0 ) {status = 0;}}}// Set data for the fake xhr objectjqXHR.status = status;jqXHR.statusText = ( nativeStatusText || statusText ) + "";// Success/Errorif ( isSuccess ) {deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );} else {deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );}// Status-dependent callbacksjqXHR.statusCode( statusCode );statusCode = undefined;if ( fireGlobals ) {globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",[ jqXHR, s, isSuccess ? success : error ] );}// CompletecompleteDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );if ( fireGlobals ) {globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );// Handle the global AJAX counterif ( !( --jQuery.active ) ) {jQuery.event.trigger("ajaxStop");}}}return jqXHR;},getJSON: function( url, data, callback ) {return jQuery.get( url, data, callback, "json" );},getScript: function( url, callback ) {return jQuery.get( url, undefined, callback, "script" );}});jQuery.each( [ "get", "post" ], function( i, method ) {jQuery[ method ] = function( url, data, callback, type ) {// Shift arguments if data argument was omittedif ( jQuery.isFunction( data ) ) {type = type || callback;callback = data;data = undefined;}return jQuery.ajax({url: url,type: method,dataType: type,data: data,success: callback});};});return jQuery;});