Rails update.js.erb not executing javascript

后端 未结 7 1884
[愿得一人]
[愿得一人] 2020-12-13 18:35

I am building a form in rails that will edit an existing question via ajax.

After the form is submitted and the question has been updated, the update method in the c

相关标签:
7条回答
  • 2020-12-13 19:13

    One more problem to be aware of is an error in your update.js file. Nothing will execute if there are any syntax errors. You can check this by going to your browser inspector and enabling Log XMLHttpRequests Then reviewing the output js file.

    0 讨论(0)
  • 2020-12-13 19:14

    Found out what it is!

    0 讨论(0)
  • 2020-12-13 19:19

    Do you work with haml, or html.erb? If the former, then this might be the solution:

    respond_to do |format|
      ...
      format.js {render layout: false}
    end
    

    I had the exact same problem, found this question early on, took another hour or so of Googling to find this question on StackOverflow that led me to it: jQuery + Ajax + Haml. js.erb files not firing

    0 讨论(0)
  • 2020-12-13 19:21

    I ran into the same issue and found this page. I tried methods listed here but found no luck. While later the following method solve my issue.

    My originally code was:

    $('#html_id').html('<%=@ruby_variable%>');
    

    And I updated it to:

    $('#html_id').html('<%=raw @ruby_variable.to_json%>');
    

    Now it works as expected.

    0 讨论(0)
  • 2020-12-13 19:22

    In your $.ajax call make sure to set the dataType option to "script" otherwise the response could be interpreted in other ways and thus not executed as JS.

    0 讨论(0)
  • 2020-12-13 19:24

    In your update.js.erb file you need to escape javascript wherever you execute ruby code.

    $('.container').empty().append('<%=
      escape_javascript(
        render 'update'
      )
    %>')
    

    This is what solved it for me ...

    0 讨论(0)
提交回复
热议问题