Rails: Pass Params Through Ajax

故事扮演 提交于 2019-12-05 03:14:58

Your data parameter is wrong.

You have

data: {'q':q},

It should be

data: {q: 'q'},

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.

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