?Briella 2011-11-30 14:27 采纳率: 0%
浏览 23

AJAX提供的Rails资源

In rails, what kind of AJAX call would need to be made in order to create and modify resources. Say if i had a resource like this

Man(age: integer, country_from:string, residence:string)

Now how would this be made through an AJAX call (like sending post to my create function, how would parameters be sent in, how would my controllers be setup). Be detailed, my AJAX is very, very, very weak. (right now i have my Man made like rails generate scaffold Man age:int country_from:string ...)

PS

Im using rails 3

  • 写回答

2条回答 默认 最新

  • weixin_33728268 2011-11-30 14:40
    关注

    So I believe there are two sides to this: the javascript and the controller changes.

    In your controller you need to ensure it can return json output (or xml or whatever your chosen ajax-y output is):

    def man
      # do your work
      return_data = {}
      # initialize your return data
      respond_to do |format|
        render :json => return_data.to_json, :layout => nil
      end
    end
    

    There are many ways to generate your json output but basically you have to make sure it's in a shape that is easily consumed on the view javascript.

    I use jQuery and here's the code to execute an ajax call:

    function foo(some_param) {
      $.ajax({
        type: 'GET',
        url: "/<controller>/man?FOO=" + some_params,
        dataType: 'json',
        success: handle_success,
        error: handle_errors
     }
    
    function handle_success(data) {
      # process return JSON. it's a javascript object corresponding to the shape
      # of your JSON. If your json was a hash server side, it will be an 'object', etc
    }
    
    function handle_error(data) {
      # handle error cases based upon failure in the infrastructure, not 
      # failure cases that you encounter due to input, etc.
    }
    

    You can tie the foo function to some button or onclick as you desire.

    I am not sure this is complete enough. Let me know if you need more detail, etc.

    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘