Made a number of syntax tweaks to ajax.js.

This commit is contained in:
John Resig 2009-07-19 19:37:11 +00:00
parent fa2d663639
commit 5272ed28bc

View file

@ -3,8 +3,9 @@ jQuery.fn.extend({
_load: jQuery.fn.load, _load: jQuery.fn.load,
load: function( url, params, callback ) { load: function( url, params, callback ) {
if ( typeof url !== "string" ) if ( typeof url !== "string" ) {
return this._load( url ); return this._load( url );
}
var off = url.indexOf(" "); var off = url.indexOf(" ");
if ( off >= 0 ) { if ( off >= 0 ) {
@ -16,7 +17,7 @@ jQuery.fn.extend({
var type = "GET"; var type = "GET";
// If the second parameter was provided // If the second parameter was provided
if ( params ) if ( params ) {
// If it's a function // If it's a function
if ( jQuery.isFunction( params ) ) { if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback // We assume that it's the callback
@ -24,10 +25,11 @@ jQuery.fn.extend({
params = null; params = null;
// Otherwise, build a param string // Otherwise, build a param string
} else if( typeof params === "object" ) { } else if ( typeof params === "object" ) {
params = jQuery.param( params ); params = jQuery.param( params );
type = "POST"; type = "POST";
} }
}
var self = this; var self = this;
@ -39,7 +41,7 @@ jQuery.fn.extend({
data: params, data: params,
complete: function(res, status){ complete: function(res, status){
// If successful, inject the HTML into all the matched elements // If successful, inject the HTML into all the matched elements
if ( status == "success" || status == "notmodified" ) if ( status === "success" || status === "notmodified" ) {
// See if a selector was specified // See if a selector was specified
self.html( selector ? self.html( selector ?
// Create a dummy div to hold the results // Create a dummy div to hold the results
@ -53,11 +55,14 @@ jQuery.fn.extend({
// If not, just inject the full result // If not, just inject the full result
res.responseText ); res.responseText );
}
if( callback ) if ( callback ) {
self.each( callback, [res.responseText, status, res] ); self.each( callback, [res.responseText, status, res] );
} }
}
}); });
return this; return this;
}, },
@ -75,7 +80,9 @@ jQuery.fn.extend({
}) })
.map(function(i, elem){ .map(function(i, elem){
var val = jQuery(this).val(); var val = jQuery(this).val();
return val == null ? null :
return val == null ?
null :
jQuery.isArray(val) ? jQuery.isArray(val) ?
jQuery.map( val, function(val, i){ jQuery.map( val, function(val, i){
return {name: elem.name, value: val}; return {name: elem.name, value: val};
@ -155,8 +162,10 @@ jQuery.extend({
// Create the request object; Microsoft failed to properly // Create the request object; Microsoft failed to properly
// implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available // implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
// This function can be overriden by calling jQuery.ajaxSetup // This function can be overriden by calling jQuery.ajaxSetup
xhr:function(){ xhr: function(){
return window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest(); return window.ActiveXObject ?
new ActiveXObject("Microsoft.XMLHTTP") :
new XMLHttpRequest();
}, },
accepts: { accepts: {
xml: "application/xml, text/xml", xml: "application/xml, text/xml",
@ -186,8 +195,8 @@ jQuery.extend({
} }
// Handle JSONP Parameter Callbacks // Handle JSONP Parameter Callbacks
if ( s.dataType == "jsonp" ) { if ( s.dataType === "jsonp" ) {
if ( type == "GET" ) { if ( type === "GET" ) {
if ( !jsre.test( s.url ) ) { if ( !jsre.test( s.url ) ) {
s.url += (/\?/.test( s.url ) ? "&" : "?") + (s.jsonp || "callback") + "=?"; s.url += (/\?/.test( s.url ) ? "&" : "?") + (s.jsonp || "callback") + "=?";
} }
@ -198,7 +207,7 @@ jQuery.extend({
} }
// Build temporary JSONP function // Build temporary JSONP function
if ( s.dataType == "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) { if ( s.dataType === "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) {
jsonp = "jsonp" + jsc++; jsonp = "jsonp" + jsc++;
// Replace the =? sequence both in the query string and the data // Replace the =? sequence both in the query string and the data
@ -220,44 +229,50 @@ jQuery.extend({
// Garbage collect // Garbage collect
window[ jsonp ] = undefined; window[ jsonp ] = undefined;
try{ delete window[ jsonp ]; } catch(e){} try{ delete window[ jsonp ]; } catch(e){}
if ( head ) if ( head ) {
head.removeChild( script ); head.removeChild( script );
}
}; };
} }
if ( s.dataType == "script" && s.cache == null ) if ( s.dataType === "script" && s.cache === null ) {
s.cache = false; s.cache = false;
}
if ( s.cache === false && type == "GET" ) { if ( s.cache === false && type === "GET" ) {
var ts = now(); var ts = now();
// try replacing _= if it is there // try replacing _= if it is there
var ret = s.url.replace(/(\?|&)_=.*?(&|$)/, "$1_=" + ts + "$2"); var ret = s.url.replace(/(\?|&)_=.*?(&|$)/, "$1_=" + ts + "$2");
// if nothing was replaced, add timestamp to the end // if nothing was replaced, add timestamp to the end
s.url = ret + ((ret == s.url) ? (/\?/.test(s.url) ? "&" : "?") + "_=" + ts : ""); s.url = ret + ((ret === s.url) ? (/\?/.test(s.url) ? "&" : "?") + "_=" + ts : "");
} }
// If data is available, append data to url for get requests // If data is available, append data to url for get requests
if ( s.data && type == "GET" ) { if ( s.data && type === "GET" ) {
s.url += (/\?/.test(s.url) ? "&" : "?") + s.data; s.url += (/\?/.test(s.url) ? "&" : "?") + s.data;
} }
// Watch for a new set of requests // Watch for a new set of requests
if ( s.global && ! jQuery.active++ ) if ( s.global && ! jQuery.active++ ) {
jQuery.event.trigger( "ajaxStart" ); jQuery.event.trigger( "ajaxStart" );
}
// Matches an absolute URL, and saves the domain // Matches an absolute URL, and saves the domain
var parts = /^(\w+:)?\/\/([^\/?#]+)/.exec( s.url ); var parts = /^(\w+:)?\/\/([^\/?#]+)/.exec( s.url );
// If we're requesting a remote document // If we're requesting a remote document
// and trying to load JSON or Script with a GET // and trying to load JSON or Script with a GET
if ( s.dataType == "script" && type == "GET" && parts if ( s.dataType === "script" && type === "GET" && parts
&& ( parts[1] && parts[1] != location.protocol || parts[2] != location.host )){ && ( parts[1] && parts[1] !== location.protocol || parts[2] !== location.host )) {
var head = document.getElementsByTagName("head")[0]; var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script"); var script = document.createElement("script");
script.src = s.url; script.src = s.url;
if (s.scriptCharset) if ( s.scriptCharset ) {
script.charset = s.scriptCharset; script.charset = s.scriptCharset;
}
// Handle Script loading // Handle Script loading
if ( !jsonp ) { if ( !jsonp ) {
@ -266,7 +281,7 @@ jQuery.extend({
// Attach handlers for all browsers // Attach handlers for all browsers
script.onload = script.onreadystatechange = function(){ script.onload = script.onreadystatechange = function(){
if ( !done && (!this.readyState || if ( !done && (!this.readyState ||
this.readyState == "loaded" || this.readyState == "complete") ) { this.readyState === "loaded" || this.readyState === "complete") ) {
done = true; done = true;
success(); success();
complete(); complete();
@ -293,24 +308,29 @@ jQuery.extend({
// Open the socket // Open the socket
// Passing null username, generates a login popup on Opera (#2865) // Passing null username, generates a login popup on Opera (#2865)
if( s.username ) if ( s.username ) {
xhr.open(type, s.url, s.async, s.username, s.password); xhr.open(type, s.url, s.async, s.username, s.password);
else } else {
xhr.open(type, s.url, s.async); xhr.open(type, s.url, s.async);
}
// Need an extra try/catch for cross domain requests in Firefox 3 // Need an extra try/catch for cross domain requests in Firefox 3
try { try {
// Set the correct header, if data is being sent // Set the correct header, if data is being sent
if ( s.data ) if ( s.data ) {
xhr.setRequestHeader("Content-Type", s.contentType); xhr.setRequestHeader("Content-Type", s.contentType);
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) { if ( s.ifModified ) {
if (jQuery.lastModified[s.url]) if ( jQuery.lastModified[s.url] ) {
xhr.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url]); xhr.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url]);
if (jQuery.etag[s.url]) }
if ( jQuery.etag[s.url] ) {
xhr.setRequestHeader("If-None-Match", jQuery.etag[s.url]); xhr.setRequestHeader("If-None-Match", jQuery.etag[s.url]);
} }
}
// Set header so the called script knows that it's an XMLHttpRequest // Set header so the called script knows that it's an XMLHttpRequest
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
@ -324,30 +344,36 @@ jQuery.extend({
// Allow custom headers/mimetypes and early abort // Allow custom headers/mimetypes and early abort
if ( s.beforeSend && s.beforeSend(xhr, s) === false ) { if ( s.beforeSend && s.beforeSend(xhr, s) === false ) {
// Handle the global AJAX counter // Handle the global AJAX counter
if ( s.global && ! --jQuery.active ) if ( s.global && ! --jQuery.active ) {
jQuery.event.trigger( "ajaxStop" ); jQuery.event.trigger( "ajaxStop" );
}
// close opended socket // close opended socket
xhr.abort(); xhr.abort();
return false; return false;
} }
if ( s.global ) if ( s.global ) {
jQuery.event.trigger("ajaxSend", [xhr, s]); jQuery.event.trigger("ajaxSend", [xhr, s]);
}
// Wait for a response to come back // Wait for a response to come back
var onreadystatechange = function(isTimeout){ var onreadystatechange = function(isTimeout){
// The request was aborted, clear the interval and decrement jQuery.active // The request was aborted, clear the interval and decrement jQuery.active
if (xhr.readyState == 0) { if ( xhr.readyState === 0 ) {
if (ival) { if ( ival ) {
// clear poll interval // clear poll interval
clearInterval(ival); clearInterval( ival );
ival = null; ival = null;
// Handle the global AJAX counter // Handle the global AJAX counter
if ( s.global && ! --jQuery.active ) if ( s.global && ! --jQuery.active ) {
jQuery.event.trigger( "ajaxStop" ); jQuery.event.trigger( "ajaxStop" );
} }
}
// The transfer is complete and the data is available, or the request timed out // The transfer is complete and the data is available, or the request timed out
} else if ( !requestDone && xhr && (xhr.readyState == 4 || isTimeout == "timeout") ) { } else if ( !requestDone && xhr && (xhr.readyState === 4 || isTimeout === "timeout") ) {
requestDone = true; requestDone = true;
// clear poll interval // clear poll interval
@ -356,12 +382,15 @@ jQuery.extend({
ival = null; ival = null;
} }
status = isTimeout == "timeout" ? "timeout" : status = isTimeout === "timeout" ?
!jQuery.httpSuccess( xhr ) ? "error" : "timeout" :
s.ifModified && jQuery.httpNotModified( xhr, s.url ) ? "notmodified" : !jQuery.httpSuccess( xhr ) ?
"error" :
s.ifModified && jQuery.httpNotModified( xhr, s.url ) ?
"notmodified" :
"success"; "success";
if ( status == "success" ) { if ( status === "success" ) {
// Watch for, and catch, XML document parse errors // Watch for, and catch, XML document parse errors
try { try {
// process the data (runs the xml through httpData regardless of callback) // process the data (runs the xml through httpData regardless of callback)
@ -372,23 +401,27 @@ jQuery.extend({
} }
// Make sure that the request was successful or notmodified // Make sure that the request was successful or notmodified
if ( status == "success" || status == "notmodified" ) { if ( status === "success" || status === "notmodified" ) {
// JSONP handles its own success callback // JSONP handles its own success callback
if ( !jsonp ) if ( !jsonp ) {
success(); success();
} else }
} else {
jQuery.handleError(s, xhr, status); jQuery.handleError(s, xhr, status);
}
// Fire the complete handlers // Fire the complete handlers
complete(); complete();
if ( isTimeout ) if ( isTimeout ) {
xhr.abort(); xhr.abort();
}
// Stop memory leaks // Stop memory leaks
if ( s.async ) if ( s.async ) {
xhr = null; xhr = null;
} }
}
}; };
if ( s.async ) { if ( s.async ) {
@ -396,13 +429,15 @@ jQuery.extend({
var ival = setInterval(onreadystatechange, 13); var ival = setInterval(onreadystatechange, 13);
// Timeout checker // Timeout checker
if ( s.timeout > 0 ) if ( s.timeout > 0 ) {
setTimeout(function(){ setTimeout(function(){
// Check to see if the request is still happening // Check to see if the request is still happening
if ( xhr && !requestDone ) if ( xhr && !requestDone ) {
onreadystatechange( "timeout" ); onreadystatechange( "timeout" );
}
}, s.timeout); }, s.timeout);
} }
}
// Send the data // Send the data
try { try {
@ -412,32 +447,38 @@ jQuery.extend({
} }
// firefox 1.5 doesn't fire statechange for sync requests // firefox 1.5 doesn't fire statechange for sync requests
if ( !s.async ) if ( !s.async ) {
onreadystatechange(); onreadystatechange();
}
function success(){ function success(){
// If a local callback was specified, fire it and pass it the data // If a local callback was specified, fire it and pass it the data
if ( s.success ) if ( s.success ) {
s.success( data, status ); s.success( data, status );
}
// Fire the global callback // Fire the global callback
if ( s.global ) if ( s.global ) {
jQuery.event.trigger( "ajaxSuccess", [xhr, s] ); jQuery.event.trigger( "ajaxSuccess", [xhr, s] );
} }
}
function complete(){ function complete(){
// Process result // Process result
if ( s.complete ) if ( s.complete ) {
s.complete(xhr, status); s.complete(xhr, status);
}
// The request was completed // The request was completed
if ( s.global ) if ( s.global ) {
jQuery.event.trigger( "ajaxComplete", [xhr, s] ); jQuery.event.trigger( "ajaxComplete", [xhr, s] );
}
// Handle the global AJAX counter // Handle the global AJAX counter
if ( s.global && ! --jQuery.active ) if ( s.global && ! --jQuery.active ) {
jQuery.event.trigger( "ajaxStop" ); jQuery.event.trigger( "ajaxStop" );
} }
}
// return XMLHttpRequest to allow aborting the request etc. // return XMLHttpRequest to allow aborting the request etc.
return xhr; return xhr;
@ -445,11 +486,14 @@ jQuery.extend({
handleError: function( s, xhr, status, e ) { handleError: function( s, xhr, status, e ) {
// If a local callback was specified, fire it // If a local callback was specified, fire it
if ( s.error ) s.error( xhr, status, e ); if ( s.error ) {
s.error( xhr, status, e );
}
// Fire the global callback // Fire the global callback
if ( s.global ) if ( s.global ) {
jQuery.event.trigger( "ajaxError", [xhr, s, e] ); jQuery.event.trigger( "ajaxError", [xhr, s, e] );
}
}, },
// Counter for holding the number of active queries // Counter for holding the number of active queries
@ -459,39 +503,43 @@ jQuery.extend({
httpSuccess: function( xhr ) { httpSuccess: function( xhr ) {
try { try {
// IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450 // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
return !xhr.status && location.protocol == "file:" || return !xhr.status && location.protocol === "file:" ||
// Opera returns 0 when status is 304 // Opera returns 0 when status is 304
( xhr.status >= 200 && xhr.status < 300 ) || xhr.status == 304 || xhr.status == 1223 || xhr.status == 0; ( xhr.status >= 200 && xhr.status < 300 ) ||
xhr.status === 304 || xhr.status === 1223 || xhr.status === 0;
} catch(e){} } catch(e){}
return false; return false;
}, },
// Determines if an XMLHttpRequest returns NotModified // Determines if an XMLHttpRequest returns NotModified
httpNotModified: function( xhr, url ) { httpNotModified: function( xhr, url ) {
var last_modified = xhr.getResponseHeader("Last-Modified"); var last_modified = xhr.getResponseHeader("Last-Modified"),
var etag = xhr.getResponseHeader("Etag"); etag = xhr.getResponseHeader("Etag");
if (last_modified) if ( last_modified ) {
jQuery.lastModified[url] = last_modified; jQuery.lastModified[url] = last_modified;
}
if (etag) if ( etag ) {
jQuery.etag[url] = etag; jQuery.etag[url] = etag;
}
// Opera returns 0 when status is 304 // Opera returns 0 when status is 304
return xhr.status == 304 || xhr.status == 0; return xhr.status === 304 || xhr.status === 0;
}, },
httpData: function( xhr, type, s ) { httpData: function( xhr, type, s ) {
var ct = xhr.getResponseHeader("content-type"), var ct = xhr.getResponseHeader("content-type"),
xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0, xml = type === "xml" || !type && ct && ct.indexOf("xml") >= 0,
data = xml ? xhr.responseXML : xhr.responseText; data = xml ? xhr.responseXML : xhr.responseText;
if ( xml && data.documentElement.nodeName == "parsererror" ) { if ( xml && data.documentElement.nodeName === "parsererror" ) {
throw "parsererror"; throw "parsererror";
} }
// Allow a pre-filtering function to sanitize the response // Allow a pre-filtering function to sanitize the response
// s != null is checked to keep backwards compatibility // s is checked to keep backwards compatibility
if ( s && s.dataFilter ) { if ( s && s.dataFilter ) {
data = s.dataFilter( data, type ); data = s.dataFilter( data, type );
} }
@ -505,7 +553,7 @@ jQuery.extend({
} }
// Get the JavaScript object, if JSON is used. // Get the JavaScript object, if JSON is used.
if ( type == "json" ) { if ( type === "json" ) {
if ( typeof JSON === "object" && JSON.parse ) { if ( typeof JSON === "object" && JSON.parse ) {
data = JSON.parse( data ); data = JSON.parse( data );
} else { } else {
@ -520,31 +568,34 @@ jQuery.extend({
// Serialize an array of form elements or a set of // Serialize an array of form elements or a set of
// key/values into a query string // key/values into a query string
param: function( a ) { param: function( a ) {
var s = [ ]; var s = [];
function add( key, value ){ function add( key, value ){
s[ s.length ] = encodeURIComponent(key) + '=' + encodeURIComponent(value); s[ s.length ] = encodeURIComponent(key) + '=' + encodeURIComponent(value);
}; }
// If an array was passed in, assume that it is an array // If an array was passed in, assume that it is an array
// of form elements // of form elements
if ( jQuery.isArray(a) || a.jquery ) if ( jQuery.isArray(a) || a.jquery ) {
// Serialize the form elements // Serialize the form elements
jQuery.each( a, function(){ jQuery.each( a, function(){
add( this.name, this.value ); add( this.name, this.value );
}); });
// Otherwise, assume that it's an object of key/value pairs // Otherwise, assume that it's an object of key/value pairs
else } else {
// Serialize the key/values // Serialize the key/values
for ( var j in a ) for ( var j in a ) {
// If the value is an array then the key names need to be repeated // If the value is an array then the key names need to be repeated
if ( jQuery.isArray(a[j]) ) if ( jQuery.isArray(a[j]) ) {
jQuery.each( a[j], function(){ jQuery.each( a[j], function(){
add( j, this ); add( j, this );
}); });
else } else {
add( j, jQuery.isFunction(a[j]) ? a[j]() : a[j] ); add( j, jQuery.isFunction(a[j]) ? a[j]() : a[j] );
}
}
}
// Return the resulting serialization // Return the resulting serialization
return s.join("&").replace(/%20/g, "+"); return s.join("&").replace(/%20/g, "+");