gpt4 book ai didi

jQuery.ajax如何使用contents属性

转载 作者:行者123 更新时间:2023-12-03 22:48:06 26 4
gpt4 key购买 nike

谁能给我一个关于如何使用 contents 属性的示例吗?

$.ajax(
{
contents : {...}
}

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

内容

字符串/正则表达式对的对象,根据给定的内容类型确定 jQuery 将如何解析响应

最佳答案

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

$.ajax() converters support mapping data types to other data types. If, however, you want to map a custom data type to a known type (e.g json), you must add a correspondance between the response Content-Type and the actual data type using the contents option:

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

因此,这意味着您的服务器响应的数据类型可能是 mycustomtype。当 AJAX 调用接收到数据时,它将看到其数据类型为 mycustomtype 并与我们设置的正则表达式(在 contents 中)匹配:/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
}

您可以编写自己的转换器函数:

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;
};

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

{
"* text": window.String,
"text html": true,
"text json": jQuery.parseJSON,
"text xml": jQuery.parseXML
}

关于jQuery.ajax如何使用contents属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15760422/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com