简体   繁体   English

如何使用jQuery将JSON请求发送到Rails

[英]How to send json request to rails using jquery

I would like to send JSON post request to rails 3 server. 我想将JSON发布请求发送到Rails 3服务器。 I have following ajax request: 我有以下ajax请求:
$.ajax({ type: 'POST',
contentType: "application/json",
url: url, data: {email: "example@test.com", password: "password"},
success: onSuccess,
error: onError,
dataType: "json"
});

However the rails server receive the data as following: 但是,rails服务器接收的数据如下:
{"_json"=>["object Object"]}
Where I want it to receive it as: 我希望它在哪里收到:
{"email"=>"exmaple@test.com", "password"=>"[FILTERED]"}

I think this is happening because the jquery wraps the data with _json object if the content type is json. 我认为这是发生的,因为如果内容类型为json,则jQuery会使用_json对象包装数据。

Does anybody know how I should do this? 有人知道我应该怎么做吗?

This turns out to be because of bugs in old version of jquery. 事实证明这是由于旧版jquery中的错误所致。 I now user jquery version 1.5 and send post request as follow: 我现在使用jquery 1.5版,并发送发帖请求,如下所示:

$.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)?

jQuery.param({email: "example@test.com", password: "password"})
==> "email=example%40test.com&password=password"

So that your ajax request becomes: 这样您的ajax请求将变为:

$.ajax({ type: 'POST',
contentType: "application/json",
url: url, data: $.param({email: "example@test.com", 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. 根据jquery文档,似乎如果将对象传递给数据,它将尝试进行一些自动反序列化。

Set processData: false and then set data to json string. 设置processData: false ,然后将数据设置为json字符串。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM