Jquery - 如何让 $.post() 使用 contentType=application/json? [英] Jquery - How to make $.post() use contentType=application/json?

查看:123
本文介绍了Jquery - 如何让 $.post() 使用 contentType=application/json?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到在 jquery 中使用 $.post() 时,默认的 contentType 是 application/x-www-form-urlencoded - 当我的 asp.net mvc 代码需要 contentType=application/json 时

I've noticed that when using $.post() in jquery that the default contentType is application/x-www-form-urlencoded - when my asp.net mvc code needs to have contentType=application/json

(有关为什么我必须使用 application/json,请参阅此问题:ASPNET MVC - 当该字段确实有值时,为什么 ModelState.IsValid 为 false 需要 x 字段"?)

(See this question for why I must use application/json: ASPNET MVC - Why is ModelState.IsValid false "The x field is required" when that field does have a value?)

如何让 $.post() 发送 contentType=application/json?我已经有大量的$.post()函数了,所以不想改成$.ajax(),因为太费时间了

How can I make $.post() send contentType=application/json? I already have a large number of $.post() functions, so I don't want to change to $.ajax() because it would take too much time

如果我尝试

$.post(url, data, function(), "json") 

它仍然有 contentType=application/x-www-form-urlencoded.那么,如果json"参数不将内容类型更改为 json,它究竟会做什么?

It still has contentType=application/x-www-form-urlencoded. So what exactly does the "json" param do if it does not change the contenttype to json?

如果我尝试

$.ajaxSetup({
  contentType: "application/json; charset=utf-8"
});

这有效,但会影响我拥有的每一个 $.get 和 $.post 并导致一些中断.

That works but affects every single $.get and $.post that I have and causes some to break.

那么有什么方法可以改变 $.post() 的行为来发送 contentType=application/json 吗?

So is there some way that I can change the behavior of $.post() to send contentType=application/json?

推荐答案

我想你可能需要

1.修改源代码,使 $.post 始终使用 JSON 数据类型,因为它实际上只是预先配置的 $.ajax 调用的快捷方式

1.Modify the source to make $.post always use JSON data type as it really is just a shortcut for a pre configured $.ajax call

或者

2.定义您自己的实用函数,它是 $.ajax 的快捷方式你要使用的配置

3.您可以通过猴子补丁使用您自己的实现覆盖$.post 函数.

3.You could overwrite the $.post function with your own implementation via monkey patching.

示例中的 JSON 数据类型是指从服务器返回的数据类型,而不是发送到服务器的格式.

The JSON datatype in your example refers to the datatype returned from the server and not the format sent to the server.

这篇关于Jquery - 如何让 $.post() 使用 contentType=application/json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆