Rails js.erb not working

自闭症网瘾萝莉.ら 提交于 2021-02-11 08:42:53

问题


I'm submitting a form, with somewhat complex nesting to a Rails controller. The Javascript is tied to the submit button as below:

    $('#new_search').submit(function() {  
    var valuesToSubmit = $(this).serializeArray();
    $.ajax({
        type: "POST",
        url: $(this).attr('action'), //sumbits it to the given url of the form
        data: valuesToSubmit,
        dataType: "POST" 
    })
    return false; // prevents normal behaviour
});

The Rails controller handles this fine and the parameters are all where they should be.

I'm then rendering a js.erb file:

 respond_to do |format|
  format.js { render '/searches/update_search_results.js.erb' } 
 end

and the log shows this has indeed rendered:

Rendered searches/update_search_results.js.erb (0.3ms)

But in this file (I've doubled checked the file name) even a simple

alert("hello world");

is not firing. There are no Javascript errors in the console log. Anyone got any suggestions? Something to do with the original Javascript that sends the Ajax request? thanks for any help


回答1:


OK, fixed it by going back to the old style :remote => true in the form definition in the view.

I thought the world had moved away from this to unobtrusive JS bouncing off the submit event. Obviously I was wrong but this solution might help someone so I'm leaving it here



来源:https://stackoverflow.com/questions/37437247/rails-js-erb-not-working

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