10

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

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

然后像这样把它们送回去:

function sendParams(q){
  $.ajax({
    url: '/mymodel/myaction',
    type: 'post',
    data: {'q':q},
    contentType: 'json'
  });
}

在我的控制器中,我尝试像使用任何其他参数一样使用它们:

MyModel.where(params[:q])

但是参数是空的,即使萤火虫在 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 子句处理吗?我该怎么做才能使 params 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 转换为参数哈希?

4

2 回答 2

6

您的数据参数错误。

你有

data: {'q':q},

它应该是

data: {q: 'q'},
于 2013-02-13T09:32:41.373 回答
6

有几个问题需要解决才能使其发挥作用。首先,q它没有作为参数发送到 Rails,即使它正在发布。原因是它被视为 JSON 数据而不是参数。我通过删除该行来解决这个问题:

contentType: 'json'

之后,AJAX 正确地发送了 'q',但 Rails 在使用它时遇到了麻烦,因为它在 JSON 中。我不得不用 解析它ActiveSupport::JSON.decode,但这会引发737: unexpected token错误。我通过 (JSONlint)[http://jsonlint.com/] 运行代码,结果发现所有的引号都被转义了。

从那里,有两个解决方案。显而易见的是这样使用.html_safe

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

但这会在用户输入引号时引起问题。更安全的替代方法是在将转义的 HTML 实体传递回 Rails 后对其进行解码,如下所示:

ActiveSupport::JSON.decode(CGI.unescapeHTML(params[:q]))

这成功了。

于 2013-02-13T14:28:13.977 回答