Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

huge revision of Ajax documentation

  • Loading branch information...
commit cd0e7317dec8a192efdd7003c9814f9ea34cacfc 1 parent 28cac0a
Mislav Marohnić mislav authored
125 ajax/_posts/1900-01-01-Z-ajax.md
View
@@ -4,77 +4,96 @@ signature: |
$.ajax(options) ⇒ XMLHttpRequest
---
-Send an Ajax request. Supports local and remote (CORS) Ajax calls, as well as JSONP.
+Perform an Ajax request. It can be to a local resource, or cross-domain via
+[HTTP access control][CORS] support in browsers or [JSONP][].
Options:
-* `type` (default `"GET"`): type of request (`GET` or `POST`)
-* `url` (defaults to current URL): URL to which the request is made.
-* `data`: data to send to server, can be a string or an object
-* `dataType` (default `"json"`): response type to be accepted from the server, `json`, `xml`, `html`, or `text`
-* `timeout` (default `0`): request timeout in milliseconds, `0` for no timeout
-* `headers`: an object containing additional headers for the Ajax request
-* `async` (default `true`): set to `false` to issue a synchronous (blocking) request
-* `global` (default `true`): trigger global Ajax events on this request
-* `context` (default `window`): context to execute callbacks in
-
-<h4>Callbacks</h4>
+* `type` (default: "GET"): HTTP request method ("GET", "POST", or other)
+* `url` (default: current URL): URL to which the request is made
+* `data` (default: none): data for the request; for GET requests it is appended
+ to query string of the URL. Non-string objects will get serialized with
+ [$.param](#$.param)
+* `contentType` (default: "application/x-www-form-urlencoded"): the Content-Type
+ of the data being posted to the server (this can also be set via `headers`)
+* `dataType` (default: none): response type to expect from the server ("json", "jsonp", "xml", "html", or "text")
+* `timeout` (default: `0`): request timeout in milliseconds, `0` for no timeout
+* `headers`: object of additional HTTP headers for the Ajax request
+* `async` (default: true): set to `false` to issue a synchronous (blocking) request
+* `global` (default: true): trigger global Ajax events on this request
+* `context` (default: window): context to execute callbacks in
+
+If the URL contains `=?` or `dataType` is "jsonp", the request is performed
+with [$.ajaxJSONP](#$.ajaxJSONP).
+
+#### Ajax callbacks
You can specify the following callback functions, which are given in order of execution:
-* `beforeSend(xhr, settings)`: executed before the request is sent. Return `false` to cancel the Ajax request.
-* `success(data, status, xhr)`: executed after request succeeds
-* `error(xhr, status, error)`: executed if there is an error (timeout, request status code is not in the HTTP 2xx range (except for `file://` URLs), or exception when parsing data)
-* `complete(xhr, status)`: executed after request is complete (both on error and success)
+1. `beforeSend(xhr, settings)`: before the request is sent. Provides access to
+ the xhr object. Return `false` from the function to cancel the request
+
+2. `success(data, status, xhr)`: when request succeeds
+
+3. `error(xhr, errorType, error)`: if there is an error (timeout, parse error,
+ or status code not in HTTP 2xx)
+
+4. `complete(xhr, status)`: after the request is complete, regardless of error
+ or success
+
+#### Ajax events
+
+These events are fired during the lifecycle of an Ajax request performed with
+the default setting of `global: true`:
+
+1. `ajaxStart` <i>(global)</i>: fired if no other Ajax requests are currently
+ active
+
+2. `ajaxBeforeSend` (data: xhr, options): before sending the request; can be
+ cancelled
+
+3. `ajaxSend` (data: xhr, options): like `ajaxBeforeSend`, but not cancellable
+
+5. `ajaxSuccess` (data: xhr, options, data): when the response is success
+
+4. `ajaxError` (data: xhr, options, error): when there was an error
+
+6. `ajaxComplete` (data: xhr, options): after request has completed, regardless
+ of error or success
+
+7. `ajaxStop` <i>(global)</i>: fired if this was the last active Ajax request
+
+By default, Ajax events are fired on the document object. However, if the
+`context` of a request is a DOM node, the events are fired on that node and will
+bubble up the DOM. The only exceptions to this are the global events `ajaxStart`
+& `ajaxStop`.
{% highlight js %}
+$(document).on('ajaxBeforeSend', function(e, xhr, options){
+ // This gets fired for every Ajax request performed on the page.
+ // The xhr object and $.ajax() options are available for editing.
+ // Return false to cancel this request.
+})
+
$.ajax({
type: 'POST',
url: '/projects',
data: { name: 'Zepto.js' },
- dataType: 'html',
- timeout: 100,
+ dataType: 'json',
+ timeout: 300,
context: $('body'),
success: function(data){
- this.append(data);
+ // Supposing this JSON payload was received:
+ // {"project": {"id": 42, "html": "<div>..." }}
+ // append the HTML to context object.
+ this.append(data.project.html)
},
error: function(xhr, type){
- alert('Error!');
+ alert('Ajax error!')
}
})
{% endhighlight %}
-<h4>Remote requests</h4>
-
-If the URL contains `=?` a <a href="http://en.wikipedia.org/wiki/JSONP">JSONP request</a> is assumed. JSONP requests use a `<script>` tag instead of a `XMLHttpRequest` and thusly are not subject to the same-origin policy that prevents normal Ajax requests from calling remote servers.
-
-To directly call a remote URL (a URL other than from the origin host of the current page) via a `XMLHttpRequest`, the called server must return a proper `Access-Control-Allow-Origin` HTTP header for the request to succeed. On cross-domain requests, Zepto automatically does not send the `X-Requested-With` header it usually sends along local Ajax requests. See <a href="http://en.wikipedia.org/wiki/Cross-origin_resource_sharing">Cross-origin resource sharing (CORS)</a> on Wikipedia for more information.
-
-<h4>Global Ajax event handlers</h4>
-
-You can register global Ajax event handlers that are triggered on every Ajax request that has the `global` option set to `true` (which is the default):
-
-{% highlight js %}
-// Ajax requests are active
-// If there are two or more concurrent requests, ajaxStart is fired only once.
-$(document).on('ajaxStart', function(settings){ ... })
-// before request is sent, return false to cancel the Ajax request
-$(document).on('ajaxBeforeSend', function(xhr, settings){ ... })
-
-// just before request is sent
-$(document).on('ajaxSend', function(xhr, settings){ ... })
-
-// timeout, request status code is not in the HTTP 2xx range
-// (except for `file://` URLs), or exception when parsing data
-$(document).on('ajaxError', function(xhr, settings, error){ ... })
-
-// successful request
-$(document).on('ajaxSuccess', function(xhr, settings, data){ ... })
-
-// request is complete (error or success)
-$(document).on('ajaxComplete', function(xhr, settings){ ... })
-
-// all active Ajax requests have completed
-$(document).on('ajaxStop', function(settings){ ... })
-{% endhighlight %}
+ [cors]: https://developer.mozilla.org/en/http_access_control
+ [jsonp]: http://json-p.org
25 ajax/_posts/1900-01-01-Z-ajaxJSONP.md
View
@@ -4,17 +4,30 @@ signature: |
$.ajaxJSONP(options) ⇒ mock XMLHttpRequest
---
-Make a <a href="http://en.wikipedia.org/wiki/JSONP">JSONP request</a>. JSONP requests use a `<script>` tag instead of a `XMLHttpRequest` and thus are not subject to the same-origin policy that prevents normal Ajax requests to call remote servers. An alternative to this is <a href="http://en.wikipedia.org/wiki/Cross-origin_resource_sharing">cross-origin remote sharing (CORS)</a>, which is also supported by Zepto.
-
-For valid `options`, see <a href="#$.ajax">$.ajax</a> (the `method` and `async` options are not supported on JSONP requests).
+Perform a [JSONP][] request to another domain. JSONP request are not performed
+with XMLHttpRequest, but by injecting a `<script>` to the document. Most
+[$.ajax](#$.ajax) options are supported, with the following considerations:
-The return value is a mock XMLHttpRequest object that only supports the `abort` method.
+* `type` is always "GET"
+* `url` needs to have the `=?` placeholder
+* `contentType`, `dataType`, `headers`, and `async` are not supported.
-{% highlight js %}
+The `?` placeholder in the URL is replaced with the dynamically generated name
+of the callback function for this request. Typically the URL should contain the
+query string such as `callback=?`; most servers expect the parameter to be
+called like that.
+
+The return value is a mock XMLHttpRequest object that only supports the
+`abort()` method.
+
+{% highlight js hl_lines=2 %}
$.ajaxJSONP({
url: 'http://example.com/projects?callback=?',
success: function(data){
- projects.push(json)
+ // data is a js object, such as Object or Array
}
})
{% endhighlight %}
+
+
+ [jsonp]: http://json-p.org
37 ajax/_posts/1900-01-01-Z-ajaxSettings.md
View
@@ -2,27 +2,18 @@
title: $.ajaxSettings
---
-Object containing the default settings for all Ajax requests.
+Object containing the default settings for Ajax requests. Most settings are
+described in [$.ajax](#$.ajax). The ones that are useful when set globally are:
-* `type` (default `"GET"`): type of request (`GET` or `POST`)
-* `timeout` (default `0`): request timeout in milliseconds, `0` for no timeout
-* `context` (default `window`): context to execute callbacks in
-* `xhr` (default: return a new XMLHttpRequest instance): override to supply your own XMLHttpRequest (or compatible object) to all Ajax requests
-* `global` (default `true`): whether to trigger global Ajax events
-* `accepts`: MIME type mapping for the `dataType` option (see below)
-
-Additionally you can specify default callbacks for `beforeSend`, `success`, `error` and `complete`. See <a href="#$.ajax">$.ajax</a> for details on these callbacks.
-
-<h4>MIME types</h4>
-
-The following MIME types are recognized by default:
-
-{% highlight js %}
-accepts: {
- script: 'text/javascript, application/javascript',
- json: 'application/json',
- xml: 'application/xml, text/xml',
- html: 'text/html',
- text: 'text/plain'
-}
-{% endhighlight %}
+* `timeout` (default: `0`): set to a non-zero value to specify a default timeout
+ for Ajax requests in milliseconds
+* `global` (default: true): set to false to prevent firing Ajax events
+* `xhr` (default: XMLHttpRequest factory): set to a function that returns
+ instances of XMLHttpRequest (or a compatible object)
+* `accepts`: MIME types to request from the server for specific `dataType`
+ values:
+ - script: "text/javascript, application/javascript"
+ - json: "application/json"
+ - xml: "application/xml, text/xml"
+ - html: "text/html"
+ - text: "text/plain"
4 ajax/_posts/1900-01-01-Z-param.md
View
@@ -2,12 +2,16 @@
title: $.param
signature: |
$.param(object, [shallow]) ⇒ string
+ $.param(array) ⇒ string
---
Serialize an object to a URL-encoded string representation for use in Ajax
request query strings and post data. If shallow is set, nested objects are
not serialized and nested array values won't use square brackets on their keys.
+Also accepts an array in [serializeArray](#serializeArray) format, where each
+item has "name" and "value" properties.
+
{% highlight js %}
$.param({ foo: { one: 1, two: 2 }})
//=> "foo[one]=1&foo[two]=2)"
7 style.css
View
@@ -96,10 +96,11 @@ h1:first-child {
font-weight: 200;
}
img[src^=logo] { max-width: 100% }
-h2 {
- font-size: 20px;
+h2 {
+ font-size: 20px;
padding-bottom: .5em;
}
+h4 { padding-top: .5em }
#sidebar hr {
margin: 25px 0 0 0;
}
@@ -119,6 +120,8 @@ ul {
li + li {
margin-top: .3em;
}
+li > ul { margin-top: .3em }
+li li { margin-top: 0 }
code, pre, tt {
font: normal 12px/18px Monaco, Consolas, "Lucida Console", monospace;
}
Please sign in to comment.
Something went wrong with that request. Please try again.