Rails远程表单引发SyntaxError

问题描述

| 我有以下表格:
<%= form_for [@commentable,Comment.new],:remote => true do |f| %>
  <%= f.text_area :body %>
  <%= f.submit \"Add your comment\" %>
<% end %>
然后是控制器(简化为基本部分):
def create
  respond_with(@comment) do |format|
    format.html { redirect_to params[:return_url] }
    format.json { render :layout => !request.xhr? }
  end
end
然后,这里是处理表格AJAX的javascript:
$(\'#new_comment\')
  .bind(\'ajax:success\',function(evt,data,status,xhr){
    var $this = $(this);

    // Append response HTML (i.e. the comment partial or helper)
    $(\'#comments ol\').append(xhr.responseText);
    $(\'#comments ol li:last-child\').effect(\"highlight\",{},3000);

    // Clear out the form so it can be used again
    $this.find(\'input:text,textarea\').val(\'\');

    // Clear out the errors from previous attempts
    $this.find(\'.errors\').empty();
  })
  .bind(\'ajax:error\',xhr,error){
    // Display the errors (i.e. an error partial or helper)
    $(this).find(\'.errors\').html(xhr.responseText);
  });
表单可以很好地提交,并且注释可以按需添加,但是Safari \的Web Inspector在提交注释表单时在我所在页面的第1行(只是doctype)上显示
SyntaxError: Parse error
,并且我不知道为什么。 甚至不知道从哪里开始。     

解决方法

我收到了该错误,这是因为远程ajax调用正在使用JavaScript,而我正在返回html。 .ajax调用默认为dataType \'script \',因此当它获得ajax结果时,它将尝试对其求值,并且任何<标记都会导致错误。 通过将视图从.js.erb更改为.html.erb并向包含
:remote => true
的链接添加
\'data-type\' => \'html\'
,我摆脱了错误。 在某些情况下,让表单本身成为JavaScript代码段可能很有意义-类似于:
$(\'#container\').replace(\"<%= escape_javascript(render(...)) %>\");
然后,您可以从链接中省略数据类型。 有关数据类型的更多信息,请参见此处。     ,尝试将
bind
呼叫与
new_comment
参考放在同一行:
$(\'#new_comment\').bind(\'ajax:success\',function(evt,data,status,xhr){
    ,我认为您看错了第1行-是否包括JavaScript文件,可能意味着其中之一是第1行。这也可能意味着第1行被发回。 老实说-尝试使用Chrome并打开调试开关,Chrome会更好地指出是哪个文件导致了问题以及在何处出现了问题。 无论如何,您都不需要将所有的JQuery放入文件中-如果您安装了正确的gem,则可以在视图中编写响应-不确定是否有帮助。     ,您的页面上是否有一个类为“ errors”的div?我遇到了非常类似的问题,并在寻找解决方案时发现了这个问题。 我的问题是,我们试图写回一个不存在的div(因为页面上的除非是.empty?)。当我们解决了这个问题时,成功回调就起作用了。     

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...