php - 如何在 $.post({}) ajax 中使用内容类型
问题描述
所以我试图使用类似下面的代码来发送帖子数据,但我需要以 json 作为格式发送。
$.post(baseUrl + 'main', {
meta: '1',
metaOut: '1',
hashcode: hashCode,
url: inputHost
}
我知道 $.ajax 方式,但是已经有很多函数在使用 $.post 所以我必须全部转换。
$.ajax({
type: "POST",
crossDomain: true,
headers: {"Content-Type": "application/x-www-form-urlencoded",},
dataType: "json",
url: baseUrl+'get-image',
data: {_token: _ourtoken, site: inputHost},
success: function (result) {
console.log(result.messages.success);
},
error: function (result) {
console.log(result.responseText);
}
});
寻找一种方法,使此 .js 文件中的所有帖子都使用 json 发送,或者对于每个 $.post,使其使用 json 格式发送。
解决方案
假设您使用的是最新的 jQuery 框架,您可以使用 jQuery 的 ajaxSetup 函数定义一个默认值,如下所示:
$.ajaxSetup({
dataType: "json"
});
有关更多信息,请参阅文档,还请注意文档不建议这样做。 https://api.jquery.com/jQuery.ajaxSetup/
请记住,$.post() 是等效于使用 $.ajax({type:"POST"}) 的简短方法。
推荐阅读
- android - 为什么 *.so 文件作为静态代码加载?
- wordpress - 如何将转发器子字段变成标签
- javascript - 材质-UI | 在 makeStyles 中使用“主题”
- c# - 无法在运行时更改游戏对象的共享材质,尽管能够通过脚本找到它
- vue.js - Vue JS 技术,用于在应用程序加载时从不同入口点获取数据
- typescript - 打字稿中空对象类型 {} 的目的是什么?
- android - 如何找到点击的地方或路径 VectorDrawable
- python - 如何在 seaborn FacetGrid 的条形顶部添加百分比?
- python - 如何制作一个按索引从列表中删除元素的函数
- javascript - 在 JavaScript 中使用 for 循环按顺序显示数字