最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to send json request to rails using jquery - Stack Overflow

programmeradmin1浏览0评论

I would like to send JSON post request to rails 3 server. I have following ajax request:
$.ajax({ type: 'POST',
contentType: "application/json",
url: url, data: {email: "[email protected]", password: "password"},
success: onSuccess,
error: onError,
dataType: "json"
});

However the rails server receive the data as following:
{"_json"=>["object Object"]}
Where I want it to receive it as:
{"email"=>"[email protected]", "password"=>"[FILTERED]"}

I think this is happening because the jquery wraps the data with _json object if the content type is json.

Does anybody know how I should do this?

I would like to send JSON post request to rails 3 server. I have following ajax request:
$.ajax({ type: 'POST',
contentType: "application/json",
url: url, data: {email: "[email protected]", password: "password"},
success: onSuccess,
error: onError,
dataType: "json"
});

However the rails server receive the data as following:
{"_json"=>["object Object"]}
Where I want it to receive it as:
{"email"=>"[email protected]", "password"=>"[FILTERED]"}

I think this is happening because the jquery wraps the data with _json object if the content type is json.

Does anybody know how I should do this?

Share Improve this question asked Apr 19, 2011 at 19:26 katsuyakatsuya 1,2043 gold badges16 silver badges21 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

This turns out to be because of bugs in old version of jquery. I now user jquery version 1.5 and send post request as follow:

$.post(url, { email: emailVal, password: passwordVal }, callback, "json").error(errorHandler);

It now works perfectly fine.

have you tried doing the serialization yourself (using jQuery.param)?

jQuery.param({email: "[email protected]", password: "password"})
==> "email=example%40test.&password=password"

So that your ajax request bees:

$.ajax({ type: 'POST',
contentType: "application/json",
url: url, data: $.param({email: "[email protected]", password: "password"}),
success: onSuccess,
error: onError,
dataType: "json"
});

According to jquery docs it seems like if you pass in an object to data it will try some automatic deserialization.

Set processData: false and then set data to json string.

http://api.jquery./jQuery.ajax/

发布评论

评论列表(0)

  1. 暂无评论