Rails 4 rendering a partial with ajax, jquery, :remote => true, and respond_to

后端 未结 3 1845
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-02 11:52

It seems like rendering a page dynamically with AJAX in response to a submitted form is common. None of the other similar questions are focused around how to do this in a g

3条回答
  •  遥遥无期
    2020-12-02 12:15

    For what it's worth (because I was tripping up on this in an app upgrade from Rails 2 to 3): you can also do it by adding an event handler that appends the returned HTML, like the old Rails 2 prototype library used to do.

    If, for instance, you're trying to take this (prepare for a runon sentence):

    form_remote_tag url: {...}, update: ...
    

    Where the response is coming in as HTML and being appended automatically, and replace it with this:

    form_tag {...}, remote: true
    

    By adding an event handler to your application.js file that simply does the same thing, appending the content to a specific element, like this:

    $("#myform").on('ajax:success', function(e, data, status, xhr) {
      $("#container").append(data);
    )};
    

    Then... you may run into the same problem I did, which was that it never fires the ajax:success event! The problem is that it's expecting JS or text in the response, but it's getting HTML. The way to fix that is to tell it that the response will be HTML using an attribute on the form tag:

    form_tag {...}, remote: true, data: {type: :html}
    

    Piece of cake!

提交回复
热议问题