Jquery - 如何使$.post()使用contentType=application/json?
Jquery - 如何使$.post()使用contentType=application/json?
我注意到使用jQuery的$.post()函数时,contentType的默认值是application/x-www-form-urlencoded。但我的ASP.NET MVC代码需要contentType=application/json。(参见此问题,了解其必须使用application/json的原因:ASPNET MVC - 当某个字段确实有值时,“x字段是必需的”,为什么ModelState.IsValid为false?)
我该如何让$.post()发送contentType=application/json呢?我已经有很多$.post()函数了,所以我不想改成$.ajax(),因为这会花费太多的时间。
如果我尝试:
$.post(url, data, function(), "json")
它仍然呈现contentType=application/x-www-form-urlencoded。那么如果“json”参数不改变内容类型,它到底是做什么的呢?
如果我尝试:
$.ajaxSetup({ contentType: "application/json; charset=utf-8" });
那是能够工作的,但会影响我所有的$.get和$.post,导致一些操作出现问题。
那么,有没有办法改变$.post()的行为,使其发送contentType=application/json呢?
admin 更改状态以发布 2023年5月21日
$.ajax({ url:url, type:"POST", data:data, contentType:"application/json; charset=utf-8", dataType:"json", success: function(){ ... } })