Fixed synchrnous requests, improved AJAX inline documentation

This commit is contained in:
Jörn Zaefferer 2006-12-15 09:13:24 +00:00
parent 18e330741f
commit 898ca3198b
3 changed files with 133 additions and 91 deletions

View file

@ -1,6 +1,13 @@
New and Noteworthy New and Noteworthy
----------------- -----------------
1.0.5
-----
- Fixed synchronous requests
- $.get, $.getIfModified, $.post, $.getScript and $.getJSON now all pass through the XMLHttpRequest as returned by $.ajax
- Improved AJAX docs (eg. more examples for $.ajax
1.0.4 1.0.4
----- -----

View file

@ -4,15 +4,15 @@ jQuery.fn.extend({
* Load HTML from a remote file and inject it into the DOM, only if it's * Load HTML from a remote file and inject it into the DOM, only if it's
* been modified by the server. * been modified by the server.
* *
* @example $("#feeds").loadIfModified("feeds.html") * @example $("#feeds").loadIfModified("feeds.html");
* @before <div id="feeds"></div> * @before <div id="feeds"></div>
* @result <div id="feeds"><b>45</b> feeds found.</div> * @result <div id="feeds"><b>45</b> feeds found.</div>
* *
* @name loadIfModified * @name loadIfModified
* @type jQuery * @type jQuery
* @param String url The URL of the HTML file to load. * @param String url The URL of the HTML file to load.
* @param Hash params A set of key/value pairs that will be sent to the server. * @param Hash params (optional) A set of key/value pairs that will be sent to the server.
* @param Function callback A function to be executed whenever the data is loaded. * @param Function callback (optional) A function to be executed whenever the data is loaded (parameters: responseText, status and response itself).
* @cat AJAX * @cat AJAX
*/ */
loadIfModified: function( url, params, callback ) { loadIfModified: function( url, params, callback ) {
@ -22,13 +22,13 @@ jQuery.fn.extend({
/** /**
* Load HTML from a remote file and inject it into the DOM. * Load HTML from a remote file and inject it into the DOM.
* *
* @example $("#feeds").load("feeds.html") * @example $("#feeds").load("feeds.html");
* @before <div id="feeds"></div> * @before <div id="feeds"></div>
* @result <div id="feeds"><b>45</b> feeds found.</div> * @result <div id="feeds"><b>45</b> feeds found.</div>
* *
* @example $("#feeds").load("feeds.html", * @example $("#feeds").load("feeds.html",
* {test: true}, * {limit: 25},
* function() { alert("load is done"); } * function() { alert("The last 25 entries in the feed have been loaded"); }
* ); * );
* @desc Same as above, but with an additional parameter * @desc Same as above, but with an additional parameter
* and a callback that is executed when the data was loaded. * and a callback that is executed when the data was loaded.
@ -36,8 +36,8 @@ jQuery.fn.extend({
* @name load * @name load
* @type jQuery * @type jQuery
* @param String url The URL of the HTML file to load. * @param String url The URL of the HTML file to load.
* @param Object params A set of key/value pairs that will be sent as data to the server. * @param Object params (optional) A set of key/value pairs that will be sent as data to the server.
* @param Function callback A function to be executed whenever the data is loaded (parameters: responseText, status and reponse itself). * @param Function callback (optional) A function to be executed whenever the data is loaded (parameters: responseText, status and response itself).
* @cat AJAX * @cat AJAX
*/ */
load: function( url, params, callback, ifModified ) { load: function( url, params, callback, ifModified ) {
@ -89,11 +89,11 @@ jQuery.fn.extend({
/** /**
* Serializes a set of input elements into a string of data. * Serializes a set of input elements into a string of data.
* This will serialize all given elements. If you need * This will serialize all given elements.
* serialization similar to the form submit of a browser, *
* you should use the form plugin. This is also true for * A serialization similar to the form submit of a browser is
* selects with multiple attribute set, only a single option * provided by the form plugin. It also takes multiple-selects
* is serialized. * into account, while this method recognizes only a single option.
* *
* @example $("input[@type=text]").serialize(); * @example $("input[@type=text]").serialize();
* @before <input type='text' name='name' value='John'/> * @before <input type='text' name='name' value='John'/>
@ -121,7 +121,6 @@ jQuery.fn.extend({
evalScripts: function() { evalScripts: function() {
return this.find('script').each(function(){ return this.find('script').each(function(){
if ( this.src ) if ( this.src )
// for some weird reason, it doesn't work if the callback is ommited
jQuery.getScript( this.src ); jQuery.getScript( this.src );
else { else {
jQuery.globalEval( this.text || this.textContent || this.innerHTML || "" ); jQuery.globalEval( this.text || this.textContent || this.innerHTML || "" );
@ -140,12 +139,14 @@ if ( jQuery.browser.msie && typeof XMLHttpRequest == "undefined" )
// Attach a bunch of functions for handling common AJAX events // Attach a bunch of functions for handling common AJAX events
/** /**
* Attach a function to be executed whenever an AJAX request begins. * Attach a function to be executed whenever an AJAX request begins
* and there is none already active.
* *
* @example $("#loading").ajaxStart(function(){ * @example $("#loading").ajaxStart(function(){
* $(this).show(); * $(this).show();
* }); * });
* @desc Show a loading message whenever an AJAX request starts. * @desc Show a loading message whenever an AJAX request starts
* (and none is already active).
* *
* @name ajaxStart * @name ajaxStart
* @type jQuery * @type jQuery
@ -250,29 +251,28 @@ new function(){
jQuery.extend({ jQuery.extend({
/** /**
* Load a remote page using an HTTP GET request. All of the arguments to * Load a remote page using an HTTP GET request.
* the method (except URL) are optional.
* *
* @example $.get("test.cgi") * @example $.get("test.cgi");
* *
* @example $.get("test.cgi", { name: "John", time: "2pm" } ) * @example $.get("test.cgi", { name: "John", time: "2pm" } );
* *
* @example $.get("test.cgi", function(data){ * @example $.get("test.cgi", function(data){
* alert("Data Loaded: " + data); * alert("Data Loaded: " + data);
* }) * });
* *
* @example $.get("test.cgi", * @example $.get("test.cgi",
* { name: "John", time: "2pm" }, * { name: "John", time: "2pm" },
* function(data){ * function(data){
* alert("Data Loaded: " + data); * alert("Data Loaded: " + data);
* } * }
* ) * );
* *
* @name $.get * @name $.get
* @type undefined * @type XMLHttpRequest
* @param String url The URL of the page to load. * @param String url The URL of the page to load.
* @param Hash params A set of key/value pairs that will be sent to the server. * @param Hash params (optional) A set of key/value pairs that will be sent to the server.
* @param Function callback A function to be executed whenever the data is loaded. * @param Function callback (optional) A function to be executed whenever the data is loaded.
* @cat AJAX * @cat AJAX
*/ */
get: function( url, data, callback, type, ifModified ) { get: function( url, data, callback, type, ifModified ) {
@ -281,9 +281,7 @@ jQuery.extend({
callback = data; callback = data;
data = null; data = null;
} }
return jQuery.ajax({
// Delegate
jQuery.ajax({
url: url, url: url,
data: data, data: data,
success: callback, success: callback,
@ -294,118 +292,109 @@ jQuery.extend({
/** /**
* Load a remote page using an HTTP GET request, only if it hasn't * Load a remote page using an HTTP GET request, only if it hasn't
* been modified since it was last retrieved. All of the arguments to * been modified since it was last retrieved.
* the method (except URL) are optional.
* *
* @example $.getIfModified("test.html") * @example $.getIfModified("test.html");
* *
* @example $.getIfModified("test.html", { name: "John", time: "2pm" } ) * @example $.getIfModified("test.html", { name: "John", time: "2pm" } );
* *
* @example $.getIfModified("test.cgi", function(data){ * @example $.getIfModified("test.cgi", function(data){
* alert("Data Loaded: " + data); * alert("Data Loaded: " + data);
* }) * });
* *
* @example $.getifModified("test.cgi", * @example $.getifModified("test.cgi",
* { name: "John", time: "2pm" }, * { name: "John", time: "2pm" },
* function(data){ * function(data){
* alert("Data Loaded: " + data); * alert("Data Loaded: " + data);
* } * }
* ) * );
* *
* @name $.getIfModified * @name $.getIfModified
* @type undefined * @type XMLHttpRequest
* @param String url The URL of the page to load. * @param String url The URL of the page to load.
* @param Hash params A set of key/value pairs that will be sent to the server. * @param Hash params (optional) A set of key/value pairs that will be sent to the server.
* @param Function callback A function to be executed whenever the data is loaded. * @param Function callback (optional) A function to be executed whenever the data is loaded.
* @cat AJAX * @cat AJAX
*/ */
getIfModified: function( url, data, callback, type ) { getIfModified: function( url, data, callback, type ) {
jQuery.get(url, data, callback, type, 1); return jQuery.get(url, data, callback, type, 1);
}, },
/** /**
* Loads, and executes, a remote JavaScript file using an HTTP GET request. * Loads, and executes, a remote JavaScript file using an HTTP GET request.
* All of the arguments to the method (except URL) are optional.
* *
* Warning: Safari <= 2.0.x is unable to evalulate scripts in a global * Warning: Safari <= 2.0.x is unable to evalulate scripts in a global
* context sychronously. If you load functions via getScript, make sure * context synchronously. If you load functions via getScript, make sure
* to call them after a delay. * to call them after a delay.
* *
* @example $.getScript("test.js") * @example $.getScript("test.js");
* *
* @example $.getScript("test.js", function(){ * @example $.getScript("test.js", function(){
* alert("Script loaded and executed."); * alert("Script loaded and executed.");
* }) * });
* *
* @name $.getScript * @name $.getScript
* @type undefined * @type XMLHttpRequest
* @param String url The URL of the page to load. * @param String url The URL of the page to load.
* @param Function callback A function to be executed whenever the data is loaded. * @param Function callback (optional) A function to be executed whenever the data is loaded.
* @cat AJAX * @cat AJAX
*/ */
getScript: function( url, callback ) { getScript: function( url, callback ) {
if(callback) return jQuery.get(url, null, callback, "script");
jQuery.get(url, null, callback, "script");
else {
jQuery.get(url, null, null, "script");
}
}, },
/** /**
* Load a remote JSON object using an HTTP GET request. * Load JSON data using an HTTP GET request.
* All of the arguments to the method (except URL) are optional.
* *
* @example $.getJSON("test.js", function(json){ * @example $.getJSON("test.js", function(json){
* alert("JSON Data: " + json.users[3].name); * alert("JSON Data: " + json.users[3].name);
* }) * });
* *
* @example $.getJSON("test.js", * @example $.getJSON("test.js",
* { name: "John", time: "2pm" }, * { name: "John", time: "2pm" },
* function(json){ * function(json){
* alert("JSON Data: " + json.users[3].name); * alert("JSON Data: " + json.users[3].name);
* } * }
* ) * );
* *
* @name $.getJSON * @name $.getJSON
* @type undefined * @type XMLHttpRequest
* @param String url The URL of the page to load. * @param String url The URL of the page to load.
* @param Hash params A set of key/value pairs that will be sent to the server. * @param Hash params (optional) A set of key/value pairs that will be sent to the server.
* @param Function callback A function to be executed whenever the data is loaded. * @param Function callback A function to be executed whenever the data is loaded.
* @cat AJAX * @cat AJAX
*/ */
getJSON: function( url, data, callback ) { getJSON: function( url, data, callback ) {
jQuery.get(url, data, callback, "json"); return jQuery.get(url, data, callback, "json");
}, },
/** /**
* Load a remote page using an HTTP POST request. All of the arguments to * Load a remote page using an HTTP POST request.
* the method (except URL) are optional.
* *
* @example $.post("test.cgi") * @example $.post("test.cgi");
* *
* @example $.post("test.cgi", { name: "John", time: "2pm" } ) * @example $.post("test.cgi", { name: "John", time: "2pm" } );
* *
* @example $.post("test.cgi", function(data){ * @example $.post("test.cgi", function(data){
* alert("Data Loaded: " + data); * alert("Data Loaded: " + data);
* }) * });
* *
* @example $.post("test.cgi", * @example $.post("test.cgi",
* { name: "John", time: "2pm" }, * { name: "John", time: "2pm" },
* function(data){ * function(data){
* alert("Data Loaded: " + data); * alert("Data Loaded: " + data);
* } * }
* ) * );
* *
* @name $.post * @name $.post
* @type undefined * @type XMLHttpRequest
* @param String url The URL of the page to load. * @param String url The URL of the page to load.
* @param Hash params A set of key/value pairs that will be sent to the server. * @param Hash params (optional) A set of key/value pairs that will be sent to the server.
* @param Function callback A function to be executed whenever the data is loaded. * @param Function callback (optional) A function to be executed whenever the data is loaded.
* @cat AJAX * @cat AJAX
*/ */
post: function( url, data, callback, type ) { post: function( url, data, callback, type ) {
// Delegate return jQuery.ajax({
jQuery.ajax({
type: "POST", type: "POST",
url: url, url: url,
data: data, data: data,
@ -420,7 +409,12 @@ jQuery.extend({
/** /**
* Set the timeout of all AJAX requests to a specific amount of time. * Set the timeout of all AJAX requests to a specific amount of time.
* This will make all future AJAX requests timeout after a specified amount * This will make all future AJAX requests timeout after a specified amount
* of time (the default is no timeout). * of time.
*
* Set to null or 0 to disable timeouts (default).
*
* You can manually abort requests with the XMLHttpRequest's (returned by
* all ajax functions) abort() method.
* *
* @example $.ajaxTimeout( 5000 ); * @example $.ajaxTimeout( 5000 );
* @desc Make all AJAX requests timeout after 5 seconds. * @desc Make all AJAX requests timeout after 5 seconds.
@ -438,18 +432,20 @@ jQuery.extend({
lastModified: {}, lastModified: {},
/** /**
* Load a remote page using an HTTP request. This function is the primary * Load a remote page using an HTTP request.
* means of making AJAX requests using jQuery. *
* This is jQuery's low-level AJAX implementation. See $.get, $.post etc. for
* higher-level abstractions.
* *
* $.ajax() returns the XMLHttpRequest that it creates. In most cases you won't * $.ajax() returns the XMLHttpRequest that it creates. In most cases you won't
* need that object to manipulate directly, but it is available if you need to * need that object to manipulate directly, but it is available if you need to
* abort the request manually. * abort the request manually.
* *
* Please note: Make sure the server sends the right mimetype (eg. xml as * Note: Make sure the server sends the right mimetype (eg. xml as
* "text/xml"). Sending the wrong mimetype will get you into serious * "text/xml"). Sending the wrong mimetype will get you into serious
* trouble that jQuery can't solve. * trouble that jQuery can't solve.
* *
* Supported datatypes (see dataType option) are: * Supported datatypes are (see dataType option):
* *
* "xml": Returns a XML document that can be processed via jQuery. * "xml": Returns a XML document that can be processed via jQuery.
* *
@ -459,25 +455,25 @@ jQuery.extend({
* *
* "json": Evaluates the response as JSON and returns a Javascript Object * "json": Evaluates the response as JSON and returns a Javascript Object
* *
* $.ajax() takes one property, an object of key/value pairs, that are * $.ajax() takes one argument, an object of key/value pairs, that are
* used to initalize the request. These are all the key/values that can * used to initalize and handle the request. These are all the key/values that can
* be passed in to 'prop': * be used:
* *
* (String) url - The URL of the page to request. * (String) url - The URL to request.
* *
* (String) type - The type of request to make (e.g. "POST" or "GET"), default is "GET". * (String) type - The type of request to make ("POST" or "GET"), default is "GET".
* *
* (String) dataType - The type of data that you're expecting back from * (String) dataType - The type of data that you're expecting back from
* the server. No default: If the server sends xml, the responseXML, otherwise * the server. No default: If the server sends xml, the responseXML, otherwise
* the responseText is is passed to the success callback. * the responseText is passed to the success callback.
* *
* (Boolean) ifModified - Allow the request to be successful only if the * (Boolean) ifModified - Allow the request to be successful only if the
* response has changed since the last request, default is false, ignoring * response has changed since the last request. This is done by checking the
* the Last-Modified header * Last-Modified header. Default value is false, ignoring the header.
* *
* (Number) timeout - Local timeout to override global timeout, eg. to give a * (Number) timeout - Local timeout to override global timeout, eg. to give a
* single request a longer timeout while all others timeout after 1 seconds, * single request a longer timeout while all others timeout after 1 seconds.
* see $.ajaxTimeout() * See $.ajaxTimeout() for global timeouts.
* *
* (Boolean) global - Wheather to trigger global AJAX event handlers for * (Boolean) global - Wheather to trigger global AJAX event handlers for
* this request, default is true. Set to false to prevent that global handlers * this request, default is true. Set to false to prevent that global handlers
@ -493,14 +489,14 @@ jQuery.extend({
* *
* (Function) complete - A function to be called when the request finishes. The * (Function) complete - A function to be called when the request finishes. The
* function gets passed two arguments: The XMLHttpRequest object and a * function gets passed two arguments: The XMLHttpRequest object and a
* string describing the type the success of the request. * string describing the type of success of the request.
* *
* (Object|String) data - Data to be sent to the server. Converted to a query * (Object|String) data - Data to be sent to the server. Converted to a query
* string, if not already a string. Is appended to the url for GET-requests. * string, if not already a string. Is appended to the url for GET-requests.
* Override processData option to prevent processing. * See processData option to prevent this automatic processing.
* *
* (String) contentType - When sending data to the server, use this content-type, * (String) contentType - When sending data to the server, use this content-type.
* default is "application/x-www-form-urlencoded", which is fine for most cases. * Default is "application/x-www-form-urlencoded", which is fine for most cases.
* *
* (Boolean) processData - By default, data passed in to the data option as an object * (Boolean) processData - By default, data passed in to the data option as an object
* other as string will be processed and transformed into a query string, fitting to * other as string will be processed and transformed into a query string, fitting to
@ -530,6 +526,24 @@ jQuery.extend({
* }); * });
* @desc Save some data to the server and notify the user once its complete. * @desc Save some data to the server and notify the user once its complete.
* *
* @example var html = $.ajax({
* url: "some.php",
* async: false
* }).responseText;
* @desc Loads data synchronously. Blocks the browser while the requests is active.
* It is better to block user interaction with others means when synchronization is
* necessary, instead to block the complete browser.
*
* @example var xmlDocument = [create xml document];
* $.ajax({
* url: "page.php",
* processData: false,
* data: xmlDocument,
* success: handleResponse
* });
* @desc Sends an xml document as data to the server. By setting the processData
* option to false, the automatic conversion of data to strings is prevented.
*
* @name $.ajax * @name $.ajax
* @type XMLHttpRequest * @type XMLHttpRequest
* @param Hash prop A set of properties to initialize the request with. * @param Hash prop A set of properties to initialize the request with.
@ -654,7 +668,6 @@ jQuery.extend({
// Stop memory leaks // Stop memory leaks
xml.onreadystatechange = function(){}; xml.onreadystatechange = function(){};
xml = null; xml = null;
} }
}; };
xml.onreadystatechange = onreadystatechange; xml.onreadystatechange = onreadystatechange;
@ -673,12 +686,15 @@ jQuery.extend({
xml = null; xml = null;
} }
}, s.timeout); }, s.timeout);
// save non-leaking reference
var xml2 = xml;
// Send the data // Send the data
xml.send(s.data); xml2.send(s.data);
// return XMLHttpRequest to allow aborting the request etc. // return XMLHttpRequest to allow aborting the request etc.
return xml; return xml2;
}, },
// Counter for holding the number of active queries // Counter for holding the number of active queries
@ -691,7 +707,6 @@ jQuery.extend({
( r.status >= 200 && r.status < 300 ) || r.status == 304 || ( r.status >= 200 && r.status < 300 ) || r.status == 304 ||
jQuery.browser.safari && r.status == undefined; jQuery.browser.safari && r.status == undefined;
} catch(e){} } catch(e){}
return false; return false;
}, },
@ -704,7 +719,6 @@ jQuery.extend({
return xml.status == 304 || xmlRes == jQuery.lastModified[url] || return xml.status == 304 || xmlRes == jQuery.lastModified[url] ||
jQuery.browser.safari && xml.status == undefined; jQuery.browser.safari && xml.status == undefined;
} catch(e){} } catch(e){}
return false; return false;
}, },

View file

@ -22,6 +22,27 @@ test("param", function() {
ok( $.param(params) == "foo[bar]=baz&foo[beep]=42&foo[quux]=All%20your%20base%20are%20belong%20to%20us", "even more arrays" ); ok( $.param(params) == "foo[bar]=baz&foo[beep]=42&foo[quux]=All%20your%20base%20are%20belong%20to%20us", "even more arrays" );
}); });
test("pass-through request object", function() {
expect(7);
stop();
var count = 0;
var success = function() {
if(count++ == 6)
start();
}
var url = "data/name.php";
ok( $.get(url, success), "get" );
ok( $.getIfModified(url, success), "getIfModified" );
ok( $.post(url, success), "post" );
ok( $.getScript("data/test.js", success), "script" );
ok( $.getJSON("data/json.php", success), "json" );
ok( $.ajax({url: url, success: success}), "generic" );
});
test("synchronous request", function() {
ok( /^{ "data"/.test( $.ajax({url: "data/json.php", async: false}).responseText ), "check returned text" );
});
test("load(String, Object, Function) - simple: inject text into DOM", function() { test("load(String, Object, Function) - simple: inject text into DOM", function() {
expect(2); expect(2);
stop(); stop();