首页 > 解决方案 > 如何在 $.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 格式发送。

标签: phpjsonajax

解决方案


假设您使用的是最新的 jQuery 框架,您可以使用 jQuery 的 ajaxSetup 函数定义一个默认值,如下所示:

$.ajaxSetup({
  dataType: "json"
});

有关更多信息,请参阅文档,还请注意文档不建议这样做。 https://api.jquery.com/jQuery.ajaxSetup/

请记住,$.post() 是等效于使用 $.ajax({type:"POST"}) 的简短方法。


推荐阅读