开发者

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:

开发者_StackOverflow社区
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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜