ruby-on-rails - Rails : Pass Params Through Ajax

标签 ruby-on-rails ajax json params

我需要通过javascript将参数传递回服务器。此刻,我将它们传递给javascript,如下所示:

sendParams("<%= params[:q].to_json %>");

然后像这样将它们发送回去:
function sendParams(q){
  $.ajax({
    url: '/mymodel/myaction',
    type: 'post',
    data: {'q':q},
    contentType: 'json'
  });
}

在我的 Controller 中,我尝试像使用其他任何参数一样使用它们:
MyModel.where(params[:q])

但是,即使Firebug在POST选项卡中显示了这些参数,参数也变空了:
q=%7B%26quot%3Bc%26quot%3B%3A%7B%26quot%3B0%26quot%3B%3A%7B%26quot%3Ba%26quot%3B%3A%7B%26quot%3B0%26quot%3B%3A%7B%26quot%3Bname%26quot%3B%3A%26quot%3Btitle%26quot%3B%7D%7D%2C%26quot%3Bp%26quot%3B%3A%26quot%3Bcont%26quot%3B%2C%26quot%3Bv%26quot%3B%3A%7B%26quot%3B0%26quot%3B%3A%7B%26quot%3Bvalue%26quot%3B%3A%26quot%3B2%26quot%3B%7D%7D%7D%7D%2C%26quot%3Bs%26quot%3B%3A%7B%26quot%3B0%26quot%3B%3A%7B%26quot%3Bname%26quot%3B%3A%26quot%3Bvotes_popularity%26quot%3B%2C%26quot%3Bdir%26quot%3B%3A%26quot%3Bdesc%26quot%3B%7D%7D%7D

知道为什么where子句不处理此信息吗?我该怎么做才能使参数Rails再次可读?

更新:
Started POST "/publications/search?scroll=active&page=6" for 127.0.0.1 at 2013-0
2-12 22:55:24 -0600
Processing by PublicationsController#index as */*
Parameters: {"scroll"=>"active", "page"=>"6"}

更新2:

这个问题显然源于contentType。当我删除它时,q作为Rails参数发送。不幸的是,q仍然是JSON,导致错误:
undefined method `with_indifferent_access' for #<String:0x686d0a8>

如何将JSON转换为参数哈希?

最佳答案

您的数据参数错误。

你有

data: {'q':q},

它应该是
data: {q: 'q'},

关于ruby-on-rails - Rails : Pass Params Through Ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14846626/

相关文章:

ruby-on-rails - 如何解决 Marshal.dump "no marshal_dump is defined for class Proc"错误

ruby-on-rails - 无法使用 cocoon 追加表中的字段

json - 如何使用 Jackson API(列表中的列表)迭代 JSON 响应?

javascript - 重新加载后 Ajax 删除元素

ajax - 为什么有 Foursquare v2 API javascript 身份验证方法?

java - 如何从java中的响应中获取一部分?

ruby - GIF下载脚本中的错误处理

html - erb 在空格处打断字符串?

javascript - Rails 5 AJAX 拒绝渲染部分内容

javascript - 用于文本区域的 Onchange AJAX 在 Safari 中不起作用