jQuery.ajax如何使用contents属性

xde*_*000 6 ajax jquery

谁能给我一个如何使用该contents属性的例子?

$.ajax(
{
   contents : {...}
}
Run Code Online (Sandbox Code Playgroud)

jQuery自己的文档仅说明以下内容:

内容

An object of string/regular-expression pairs that determine how jQuery will parse the response, given its content type

Amy*_*Amy 6

来自http://api.jquery.com/jQuery.ajax/:

$ .ajax()转换器支持将数据类型映射到其他数据类型.但是,如果要将自定义数据类型映射到已知类型(例如json),则必须使用contents选项在响应Content-Type和实际数据类型之间添加对应关系:

$.ajaxSetup({
  contents: {
    mycustomtype: /mycustomtype/
  },
  converters: {
    "mycustomtype json": function ( result ) {
      // do stuff
      return newresult;
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

那么,这意味着您的服务器响应的数据类型可能是什么mycustomtype.当AJAX调用收到数据时,它会看到它的数据类型mycustomtype与我们设置的正则表达式(内容中)相匹配:/mycustomtype/并将数据抛出到我们指定的转换器中,例如.mycustomtype json()将尝试将数据转换为json.

详细说明转换器:

这converters["mycustomtype json"]意味着当您想要转换mycustomtype为json格式时,将执行此处指定的函数,因此该函数的内容将执行将返回的解析JSON.您可以指定其他转换类型,例如.

converters: {
    "mycustomtype json": converterFromCustomTypeToJson,      // mycustomtype -> json
    "mycustomtype jsonp": converterFromCustomTypeToJsonP,    // mycustomtype -> jsonp
    "mycustomtype text": converterFromCustomTypeToText,      // mycustomtype -> text 
    "text mycustomtype": converterFromTextToCustomType       // text -> mycustomtype 
}
Run Code Online (Sandbox Code Playgroud)

你会编写自己的转换器功能:

var converterFromCustomTypeToJson = function(result) {
        var jsonResult = ...
        /* do conversion to JSON */
        return jsonResult;
    },
    converterFromCustomTypeToJsonP = function(result) {
        var jsonPResult = ...
        /* do conversion to JSONP */
        return jsonPResult;
    },
    converterFromCustomTypeToText = function(result) {
        var textResult = ...
        /* do conversion to text */
        return textResult;
    },
    converterFromTextToCustomType = function(result) {
        var customResult = ...
        /* do conversion to mycustomtype */
        return customResult;
    };
Run Code Online (Sandbox Code Playgroud)

您还希望避免弄乱默认转换器,它们是:

{
    "* text": window.String, 
    "text html": true, 
    "text json": jQuery.parseJSON, 
    "text xml": jQuery.parseXML
}
Run Code Online (Sandbox Code Playgroud)