jQuery.ajaxTransport()| jqueryAPI 2.2 中文手册- AspRain.cn 致力于Web开发技术翻译整理

jQuery API 2.2.0

jQuery.ajaxTransport()| jqueryAPI 2.2 中文手册- AspRain.cn 致力于Web开发技术翻译整理

jQuery.ajaxTransport()

分类:Ajax > 底层接口

创建一个对象,用来操作Ajax数据的实际传输。

返回: undefined

jQuery.ajaxTransport( dataType, handler )

描述:Creates an object that handles the actual transmission of Ajax data.

加入于: 1.5
jQuery.ajaxTransport( dataType, handler )
  • dataType
    类型:String
    A string identifying the data type to use
  • handler
    类型:FunctionPlainObject options, PlainObject originalOptions, jqXHR jqXHR )
    A handler to return the new transport object to use with the data type provided in the first argument.

A transport is an object that provides two methods, send and abort, that are used internally by $.ajax() to issue requests. A transport is the most advanced way to enhance $.ajax() and should be used only as a last resort when prefilters and converters are insufficient.

Since each request requires its own transport object instance, transports cannot be registered directly. Therefore, you should provide a function that returns a transport instead.

Transports factories are registered using $.ajaxTransport(). A typical registration looks like this:

$.ajaxTransport( dataType, function( options, originalOptions, jqXHR ) {
  if( /* transportCanHandleRequest */ ) {
    return {
      send: function( headers, completeCallback ) {
        // Send code
      },
      abort: function() {
        // Abort code
      }
    };
  }
});

其中

  • options是关于HTTP请求的选项
  • originalOptions are the options as provided to the $.ajax() method, unmodified and, thus, without defaults from ajaxSettings
  • jqXHR is the jqXHR object of the request
  • headers is an object of (key-value) request headers that the transport can transmit if it supports it
  • completeCallback is the callback used to notify Ajax of the completion of the request

completeCallback has the following signature:

function( status, statusText, responses, headers ) {}

其中

  • status is the HTTP status code of the response, like 200 for a typical success, or 404 for when the resource is not found.
  • statusText is the statusText of the response.
  • responses (Optional) is An object containing dataType/value that contains the response in all the formats the transport could provide (for instance, a native XMLHttpRequest object would set responses to { xml: XMLData, text: textData } for a response that is an XML document)
  • headers (Optional) is a string containing all the response headers if the transport has access to them (akin to what XMLHttpRequest.getAllResponseHeaders() would provide).

Just like prefilters, a transport's factory function can be attached to a specific dataType:

$.ajaxTransport( "script", function( options, originalOptions, jqXHR ) {
  // Will only be called for script requests
});

The following example shows how a minimal image transport could be implemented:

$.ajaxTransport( "image", function( s ) {
  if ( s.type === "GET" && s.async ) {
    var image;
    return {
      send: function( _ , callback ) {
        image = new Image();
        function done( status ) {
          if ( image ) {
            var statusText = ( status === 200 ) ? "success" : "error",
              tmp = image;
            image = image.onreadystatechange = image.onerror = image.onload = null;
            callback( status, statusText, { image: tmp } );
          }
        }
        image.onreadystatechange = image.onload = function() {
          done( 200 );
        };
        image.onerror = function() {
          done( 404 );
        };
        image.src = s.url;
      },
      abort: function() {
        if ( image ) {
          image = image.onreadystatechange = image.onerror = image.onload = null;
        }
      }
    };
  }
});

Handling Custom Data Types

The jQuery Ajax implementation comes with a set of standard dataTypes, such as text, json, xml, and html.

Use the converters option in $.ajaxSetup() to augment or modify the data type conversion strategies used by $.ajax().

The unminified jQuery source itself includes a list of default converters, which effectively illustrates how they can be used:

// List of data converters
// 1) Key format is "source_type destination_type"
//    (a single space in-between)
// 2) The catchall symbol "*" can be used for source_type
converters: {
  // Convert anything to text
  "* text": window.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
}

When you specify a converters option globally in $.ajaxSetup() or per call in $.ajax(), the object will map onto the default converters, overwriting those you specify and leaving the others intact.

For example, the jQuery source uses $.ajaxSetup() to add a converter for "text script":

jQuery.ajaxSetup({
  accepts: {
    script: "text/javascript, application/javascript"
  },
  contents: {
    script: /javascript/
  },
  converters: {
    "text script": jQuery.globalEval
  }
});

如果网页上不能运行示例,请点击http://www.asprain.cn/jQueryAPI/jquery.ajaxtransport.htm查看示例。

如果你觉得本文档对你有用,欢迎给翻译作者支付宝打赏,支持翻译作者源源不断翻译更多有用的技术文档。