weixin_33705053 2014-04-26 01:43 采纳率: 0%
浏览 27

Rails AJAX快捷方式?

Using remote:true on a form, or something, and responding from the controller with :js, we can tell rails to execute some javascript file.

If you're destroying a user, for example. You'd have the User controller, and the Destroy action. You'd then have a file views/users/destroy.js.erb with something along the lines of:

$("ul#users").html("<%= j render partial: 'user_list' %>");

My question is... Is there a shortcut to just put that javascript in the controller, so that I don't have to have these tiny files littered about my app? If I'm only rendering a partial with some instance variables, and nothing else, I'd like to see something like:

respond_with render :js, with: 'partial_foo', on: '#selector .bar'

Is there such a shortcut?

  • 写回答

1条回答 默认 最新

  • weixin_33709609 2014-04-26 12:47
    关注

    The only shortcut I could recommend for you is to use json and handle the response with your unobtrusive JS:

    #view
    <%= form_for @variable, remote: :true, method: :json %>
    
    #controller
    respond_to :json, :html
    
    def action
        respond_with @variable
    end
    

    JSON sends small serialized data objects, meaning you won't have to handle any files, and can handle the data as required:

    #app/assets/javascripts/application.js
    $(element).on("ajax:success", function(data) {
        message = JSON.stringify(data);
        alert(message.attribute);
    });
    

    If you like this idea, I can come back with some ideas for handling the partial

    评论

报告相同问题?

悬赏问题

  • ¥15 已知平面坐标系(非直角坐标系)内三个点的坐标,反求两坐标轴的夹角
  • ¥15 webots有问题,无响应
  • ¥15 数据量少可以用MK趋势分析吗
  • ¥15 使用VH6501干扰RTR位,CANoe上显示的错误帧不足32个就进入bus off快慢恢复,为什么?
  • ¥15 大智慧怎么编写一个选股程序
  • ¥100 python 调用 cgps 命令获取 实时位置信息
  • ¥15 两台交换机分别是trunk接口和access接口为何无法通信,通信过程是如何?
  • ¥15 C语言使用vscode编码错误
  • ¥15 用KSV5转成本时,如何不生成那笔中间凭证
  • ¥20 ensp怎么配置让PC1和PC2通讯上