简体   繁体   English

带有Rails 3和jQuery的AJAX?

[英]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. 我一直在尝试使用Rails 3和jQuery制作基于控制台的计算器(类似于Try Ruby )。 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. 为此,我一直在尝试使用AJAX,以便控制台在您每次输入enter时都会发送JSON或XML,它会等待,从服务器接收响应并呈现它。

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. 我在Google上的搜索仅导致涉及事物客户端的教程,而其他教程仅涉及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. 我不知道要为Rails代码做什么。

So how do I go about implementing AJAX with Rails and jQuery? 那么,如何使用Rails和jQuery实现AJAX?

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 ) 在您的rails控制器中(您已将其映射到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. 最终,您的ajax调用将像其他任何Web请求一样触发控制器操作。 Your controller can respond with JSON or XML or even determine the response format by the extension on the url. 您的控制器可以使用JSON或XML进行响应,甚至可以通过URL上的扩展名确定响应格式。

Good Luck. 祝好运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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