【问题标题】:How to send json request to rails using jquery如何使用 jquery 向 Rails 发送 json 请求
【发布时间】:2011-08-08 23:00:30
【问题描述】:

我想向 rails 3 服务器发送 JSON 发布请求。我有以下 ajax 请求:
$.ajax({ type: 'POST',
contentType: "application/json",
url: url, data: {email: "example@test.com", password: "password"},
success: onSuccess,
error: onError,
dataType: "json"
});

但是,rails 服务器接收到的数据如下:
{"_json"=>["object Object"]}
我希望它在哪里接收它:
{"email"=>"exmaple@test.com", "password"=>"[FILTERED]"}

我认为这是因为如果内容类型是 json,jquery 会使用 _json 对象包装数据。

有人知道我应该怎么做吗?

【问题讨论】:

    标签: javascript jquery ruby-on-rails ajax json


    【解决方案1】:

    这原来是因为旧版本的 jquery 中的错误。我现在使用 jquery 1.5 版并发送帖子请求如下:

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

    现在可以正常使用了。

    【讨论】:

      【解决方案2】:

      您是否尝试过自己进行序列化(使用 jQuery.param)?

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

      这样你的ajax请求就变成了:

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

      【讨论】:

      • 其实jquery默认对传入的数据进行序列化。
      • @knoguchi - 是的 - jQuery.param 是 jQuery 用来序列化对象的。我只是想知道在其他地方进行序列化(而不是 .ajax 自己做)是否有助于解决问题。
      • 感谢您的建议。我已按照您的建议尝试手动序列化,但不幸的是它没有改变任何东西。
      【解决方案3】:

      根据 jquery 文档,如果您将对象传递给数据,它似乎会尝试一些自动反序列化。

      设置processData: false,然后设置数据为json字符串。

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

      【讨论】:

      • 感谢您的回答。我已经尝试过不反序列化它,但这不是问题。
      猜你喜欢
      • 1970-01-01
      • 2019-05-13
      • 1970-01-01
      • 2012-08-08
      • 1970-01-01
      • 1970-01-01
      • 2011-06-13
      • 2012-01-03
      • 1970-01-01
      相关资源
      最近更新 更多