How to update front-end content after that a form

2019-04-11 11:25发布

I am using Ruby on Rails 3.2.2 and the jQuery-Rails 2.0.2 gem (including the jQuery UI). I have a jQuery UI Dialog window that is open when I click on a "new comment" link present in the front-end content. When the dialog window is open it is performed a AJAX HTTP request to a my controller action that make it to render and "populate" the modal window body-content with a HTML form.

I would like to implement my view so that after the form is successfully submitted the front-end content change this way: the trigger link text change form "new comment" to "edit comment".

How can I make that? What do you advice about?


Note: The form is submitted in turn by performing a AJAX HTTP request.

1条回答
放我归山
2楼-- · 2019-04-11 11:45

It all depends on how you submit that form to the server.

If the form you are submitting has set the :remote => true attribute it will be sent to the server through an AJAX call and the server will be able to do differentiate it from a regular non-ajax form request:

respond_to do |format|
  format.js  #this renders the <actionname>.js.erb file and executes it on the client
end

The jquery_ujs helper will then execute javascript code that the server returned to him.

You can just write arbitrary JavaScript code in your <actionname>.js.erb file that could look like this:

$('#trigger_link').text('edit comment');

If you are not using the remote form but rather do a normal $.ajax call you can simply hook into the success callback that jQuery provides, but I guess that's obvious.

Update:

Seems like the problem is that you don't know what link triggered the opening of the Dialog.

Usually somewhere you have a jQuery function that opens the dialog for you. When rendering the initial list that contains the trigger links I assume you have some way of differentiating them from other links on the page (maybe through a css class like .trigger).

you can then do:

$('.trigger').click(function() {
  window.trigger_link = this;
});

Note that this little snippet above does not overwrite your existing click event handler that opens the popup. It gets executed too.

So now that we keep track of the link that opened the window (the window opens on clicking the trigger link - and we always save the last clicked trigger link) we can do the following once the form has been submitted:

$(window.trigger_link).text('edit comment');

Since window.trigger_link refers to the correct link.

查看更多
登录 后发表回答