简体   繁体   中英

How to use the jQuery AJAX request and the Ruby on Rails 'render' method togheter?

I am using Ruby on Rails 3.0.7 and jQuery 1.6.1 and I would like to know how to handle response xhr , status and ex variables after an AJAX request.

The AJAX request is:

$jQuery.ajax({
  type:    "POST",
  url:     "<request_to_the_controller_method>", // see the code below
  error: function(xhr, status, ex) {
    // handling with 'xhr', 'status' and 'ex' variables
  }
  success: function(jqXHR, status, ex) {
    // handling with 'xhr', 'status' and 'ex' variables
  }
});

In the controller I have:

respond_to do |format|
  format.js { 
    render ... # here should be properly stated the Ruby on Rails 'render' method 
    :status => 200 
   }
end

How SHOULD be stated in the controller the render method to respond to the AJAX request so that it is possible to handle response values ( xhr , status and ex variables) in the error or success section of the AJAX request? Then, how can I handle the response values after I retrieved those (for example to show those values in an alert message)?

In few worlds, what I would like to do is (in the controller) to respond to an AJAX request with some data and then (on the other side) handle this data.

See

How do you handle Rail's flash with Ajax requests?

and

Error Handling with Ajax in Rails 3

as well for details. Here's an excellent article on the topic of rails, the Rails jQuery UJS driver, jQuery, and rails.js

  1. It finds remote links, forms, and inputs, and overrides their click events to submit to the server via AJAX.
  2. It triggers six javascript events to which you can bind callbacks to work with and manipulate the AJAX response.

And then the article walks through how to do all this using jQuery, UJS and rails.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM