$.post() 的行为与 $.ajax 不同(相同的参数)
我遇到了一些奇怪的事情,我想揭露并知道是否有人对此做出解释。
一段时间前,我有一个简单的帖子:
$.post("/Route/Save", { myObj: JSON.stringify(myObj), accessToken: getAccessToken()}, function(data)
{
//do stuff
});
它工作得很好,现在不起作用,并且只有 accessToken 参数在路由控制器中正确接收,
我将其更改为:
$.ajax({
url: "/Route/Save",
data: '{ myObj:' + JSON.stringify(myObj) + ',accessToken:"' + getAccessToken()+'"}',
type: 'POST',
datatype: 'JSON',
contentType: 'application/json',
success: function (data)
{
//Do stuff
}
});
现在它工作了。我正在使用 Firefox 4 和 IE9,并且相信原因与浏览器发送编码信息的方式有关...在 $.post() 情况下,它看起来像以 application/x-www-form 形式发送数据-urlencoded
我很高兴收到你们的来信!
问候, 字节从机
I came across something weird, that I want to expose and know if someone as an explanation for it.
Some time back i had a simple post:
$.post("/Route/Save", { myObj: JSON.stringify(myObj), accessToken: getAccessToken()}, function(data)
{
//do stuff
});
and it was working nicely, now doesn't work, and only the accessToken paramenter is correctly received in the route controller
I changed it to:
$.ajax({
url: "/Route/Save",
data: '{ myObj:' + JSON.stringify(myObj) + ',accessToken:"' + getAccessToken()+'"}',
type: 'POST',
datatype: 'JSON',
contentType: 'application/json',
success: function (data)
{
//Do stuff
}
});
And now it works. I'm using firefox 4 and IE9 and believe the reason is connected to the way the browser is sending the info encoded... in the $.post() case it looks like it sends the data as application/x-www-form-urlencoded
I'll be glad to hear from you guys!
Regards,
byte_slave
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不知道为什么它之前可以工作;也许 jQuery 更新改变了行为?
至于您关于内容类型的问题, $.post 是 $.ajax 的简写包装器,来自 $.ajax api页面,contentType的默认值为'application/x-www-form-urlencoded'。
AFAIK,您不能使用 $.post() 指定 contentType。但我可能是错的。
I'm not sure why it was working before; perhaps a jQuery update changed behaviour?
As to your question on the content-type, $.post is a shorthand wrapper around $.ajax, and from the $.ajax api page, the default value for the contentType is 'application/x-www-form-urlencoded'.
AFAIK, you can't specify the contentType using $.post(). I could be wrong though.
$.ajax 的等价物应该是
The equivalent with $.ajax should be