简体   繁体   中英

AJAX with Rails 3 and jQuery?

I've been trying to make a console-based calculator (kind of like Try Ruby ) in using Rails 3 and jQuery. To do so, I've been trying use AJAX so that the console sends JSON or XML whenever you type enter, it waits, receives the response from the server and renders it.

Unfortunately, I have no clue as to where to start. My Google searching has lead to only tutorials that deal with the client side of things, and other tutorials only address Rails 2.

My client-side code is something like this:

function evaluate(line, report) {
  // ajaxy stuff goes here
  report("Whatever stuff I get back"); // this will display on console
}

I have no idea on what to do for the Rails code.

So how do I go about implementing AJAX with Rails and jQuery?

You probably want to do something like this

in your client code:

function evaluate(line, report) {
  // ajaxy stuff goes here
  $.post("/path/to/controller/action.json", { line: line, report: report } ,function(response){
    //process JSON response here
  });
}

in your rails controller (which you will have mapped to http://yourserver/path/to/controller/action )

def action_called
  # do stuff with params[:line] and params[:report]

  respond_to do |type|
    type.html # render html view 
    type.json { render :json => { @response_data_as_a_hash }.to_json }
  end
end

Perhaps start here

Ultimately your ajax call will hit a controller action just like any other web request. Your controller can respond with JSON or XML or even determine the response format by the extension on the url.

Good Luck.

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