ドキュメント

Ajax/jQuery.ajax

From jQuery JavaScript Library

Jump to: navigation, search

« Back to Ajax

jQuery.ajax( options )

Load a remote page using an HTTP request.
This is jQuery's low-level AJAX implementation. See $.get, $.post etc. for higher-level abstractions that are often easier to understand and use, but don't offer as much functionality (such as error callbacks).

$.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 abort the request manually.

$.ajax() takes one argument, an object of key/value pairs, that are used to initialize and handle the request. See the Options tab for a full list of the key/values that can be used.

Note: If you specify the dataType option, described in the Options section, make sure the server sends the correct MIME type in the response (eg. xml as "text/xml"). Sending the wrong MIME type can lead to unexpected problems in your script. See Specifying the Data Type for AJAX Requests for more information.

Note: All remote (not on the same domain) requests should be specified as GET when 'script' or 'jsonp' is the dataType (because it loads script using a DOM script tag). Ajax options that require an XMLHttpRequest object are not available for these requests. The complete and success functions are called on completion, but do not receive an XHR object; the beforeSend and dataFilter functions are not called.

As of jQuery 1.2, you can load JSON data located on another domain if you specify a JSONP callback, which can be done like so: "myurl?callback=?". jQuery automatically replaces the ? with the correct method name to call, calling your specified callback. Or, if you set the dataType to "jsonp" a callback will be automatically added to your Ajax request.
Arguments:
optionsOptions
A set of key/value pairs that configure the Ajax request. All options are optional. A default can be set for any option with $.ajaxSetup().
Options:

NameType
asyncBooleanDefault: true
By default, all requests are sent asynchronous (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.
beforeSendFunction
A pre-callback to modify the XMLHttpRequest object before it is sent. Use this to set custom headers etc. The XMLHttpRequest is passed as the only argument. This is an Ajax Event. You may return false in function to cancel the request.

function (XMLHttpRequest) {
  this; // the options for this ajax request
}

cacheBooleanDefault: true, false for dataType "script" and "jsonp"
Added in jQuery 1.2, if set to false it will force the pages that you request to not be cached by the browser.
completeFunction
A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The XMLHttpRequest object and a string describing the type of success of the request. This is an Ajax Event.

function (XMLHttpRequest, textStatus) {
  this; // the options for this ajax request
}

contentTypeStringDefault: "application/x-www-form-urlencoded"
When sending data to the server, use this content-type. Default is "application/x-www-form-urlencoded", which is fine for most cases.
dataObject, String
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key i.e. {foo:["bar1", "bar2"]} becomes '&foo=bar1&foo=bar2'.
dataFilterFunction
A function to be used to handle the raw responsed data of XMLHttpRequest.This is a pre-filtering function to sanitize the response.You should return the sanitized data.The function gets passed two arguments: The raw data returned from the server, and the 'dataType' parameter.

function (data, type) {
  // do something
  // return the sanitized data
  return data;
}

dataTypeStringDefault: Intelligent Guess (xml or html)
The type of data that you're expecting back from the server. If none is specified, jQuery will intelligently pass either responseXML or responseText to your success callback, based on the MIME type of the response. The available types (and the result passed as the first argument to your success callback) are:

  • "xml": Returns a XML document that can be processed via jQuery.
  • "html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
  • "script": Evaluates the response as JavaScript and returns it as plain text. Disables caching unless option "cache" is used. Note: This will turn POSTs into GETs for remote-domain requests.
  • "json": Evaluates the response as JSON and returns a JavaScript Object.
  • "jsonp": Loads in a JSON block using JSONP. Will add an extra "?callback=?" to the end of your URL to specify the callback. (Added in jQuery 1.2)
  • "text": A plain text string.
errorFunction
A function to be called if the request fails. The function is passed three arguments: The XMLHttpRequest object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror". This is an Ajax Event.

function (XMLHttpRequest, textStatus, errorThrown) {
  // typically only one of textStatus or errorThrown 
  // will have info
  this; // the options for this ajax request
}

globalBooleanDefault: true
Whether to trigger global AJAX event handlers for this request. The default is true. Set to false to prevent the global handlers like ajaxStart or ajaxStop from being triggered. This can be used to control various Ajax Events.
ifModifiedBooleanDefault: false
Allow the request to be successful only if the response has changed since the last request. This is done by checking the Last-Modified header. Default value is false, ignoring the header.
jsonpString
Override the callback function name in a jsonp request. This value will be used instead of 'callback' in the 'callback=?' part of the query string in the url for a GET or the data for a POST. So {jsonp:'onJsonPLoad'} would result in 'onJsonPLoad=?' passed to the server.
passwordString
A password to be used in response to an HTTP access authentication request.
processDataBooleanDefault: true
By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send DOMDocuments, or other non-processed data, set this option to false.
scriptCharsetString
Only for requests with 'jsonp' or 'script' dataType and GET type. Forces the request to be interpreted as a certain charset. Only needed for charset differences between the remote and local content.
successFunction
A function to be called if the request succeeds. The function gets passed two arguments: The data returned from the server, formatted according to the 'dataType' parameter, and a string describing the status. This is an Ajax Event.

function (data, textStatus) {
  // data could be xmlDoc, jsonObj, html, text, etc...
  this; // the options for this ajax request
}

timeoutNumber
Set a local timeout (in milliseconds) for the request. This will override the global timeout, if one is set via $.ajaxSetup. For example, you could use this property to give a single request a longer timeout than all other requests that you've set to time out in one second. See $.ajaxSetup() for global timeouts.
typeStringDefault: "GET"
The type of request to make ("POST" or "GET"), default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.
urlStringDefault: The current page
The URL to request. This *must* be a string (e.g., document.location.href) and not a Location object (e.g., document.location)
usernameString
A username to be used in response to an HTTP access authentication request.
xhrFunction
Callback for creating the XMLHttpRequest object. Defaults to the ActiveXObject when available (IE), the XMLHttpRequest otherwise. Override to provide your own implementation for XMLHttpRequest or enhancements to the factory.It's not available in jQuery 1.2.6 and in any early version.
Examples:
Load and execute a JavaScript file.

$.ajax({
  type: "GET",
  url: "test.js",
  dataType: "script"
});

Save some data to the server and notify the user once it's complete.

 $.ajax({
   type: "POST",
   url: "some.php",
   data: "name=John&location=Boston",
   success: function(msg){
     alert( "Data Saved: " + msg );
   }
 });

Retrieve the latest version of an HTML page.

$.ajax({
  url: "test.html",
  cache: false,
  success: function(html){
    $("#results").append(html);
  }
});

Loads data synchronously. Blocks the browser while the requests is active. It is better to block user interaction by other means when synchronization is necessary.

 var html = $.ajax({
  url: "some.php",
  async: false
 }).responseText;

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.

 var xmlDocument = [create xml document];
 $.ajax({
   url: "page.php",
   processData: false,
   data: xmlDocument,
   success: handleResponse
 });

Sends an id as data to the server, save some data to the server and notify the user once it's complete.

 bodyContent = $.ajax({
      url: "script.php",
      global: false,
      type: "POST",
      data: ({id : this.getAttribute('id')}),
      dataType: "html",
      success: function(msg){
         alert(msg);
      }
   }
).responseText;

NameType