开发者

$.post() behaves different than $.ajax( same paramenters )

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


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.


The equivalent with $.ajax should be

$.ajax({
    url: "/Route/Save",
    data: { myObj: JSON.stringify(myObj), accessToken: getAccessToken()},
    type: 'POST',       
    success: function (data)
    {
        //Do stuff
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜