Rails: Pass Params Through Ajax

China☆狼群 提交于 2019-12-22 04:26:31

问题


I need to pass params through javascript back to the server. At the moment, I pass them into javascript like so:

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

And then send them back like this:

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

In my controller, I try to use them like I would any other params:

MyModel.where(params[:q])

But the params are coming back empty, even though firebug shows this in the POST tab:

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

Any idea why this information isn't getting processed by the where clause? What can I do to make the params Rails readable again?

UPDATE:

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"}

UPDATE 2:

The problem is apparently stemming from contentType. When I remove it, then q is sent as a Rails parameter. Unfortunately, q is still in JSON, resulting in the error:

undefined method `with_indifferent_access' for #<String:0x686d0a8>

How can I convert JSON to a params hash?


回答1:


Your data parameter is wrong.

You have

data: {'q':q},

It should be

data: {q: 'q'},



回答2:


There were a couple of issues that needed to be resolved for this to work. First, q wasn't being sent as a parameter to Rails, even though it was posting. The reason was because it was being treated as JSON data rather than as a parameter. I fixed this by removing the line:

contentType: 'json'

After that, the AJAX properly sent 'q', but Rails had trouble using it as it was in JSON. I had to parse it with ActiveSupport::JSON.decode, but this was throwing a 737: unexpected token error. I ran the code through (JSONlint)[http://jsonlint.com/], and it turns out that all the quotation marks had been escaped.

From there, there were two solutions. The obvious one was to use .html_safe like so:

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

But this caused problems when the user inputed quotes. The safer alternative was to decode the escaped HTML entities after they were passed back to Rails like so:

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

And this did the trick.



来源:https://stackoverflow.com/questions/14846626/rails-pass-params-through-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!