更新时间:2023-10-25 22:23:10
要解决此问题,需要解决一些问题.首先,q
并没有作为参数发送到Rails,即使它正在发布.原因是因为它被视为JSON数据而不是参数.我通过删除以下行来解决此问题:
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'
此后,AJAX正确发送了"q",但Rails像在JSON中那样使用它时遇到了麻烦.我必须用ActiveSupport::JSON.decode
进行解析,但这引发了737: unexpected token
错误.我通过(JSONlint)[http://jsonlint.com/]运行了代码,结果发现所有引号均已转义.
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.
从那里开始,有两种解决方案.显而易见的方法是像这样使用.html_safe
:
From there, there were two solutions. The obvious one was to use .html_safe
like so:
sendParams("<%= params[:q].to_json.html_safe %>");
但这在用户输入引号时引起问题.更安全的选择是像这样将转义的HTML实体传递回Rails后对其进行解码:
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]))
这成功了.