?Briella 2012-09-11 22:11 采纳率: 0%
浏览 26

Ajax和Json与Rails

I followed Hartl's Rails tutorial where he does Ajax using RJS and sending javascript in the response to be executed on the client side to edit the DOM.

But what do you do if you want just JSON sent in the response and not send javascript. This also means the javascript to manipulate the DOM should already be in the html file on the client. Is there a tutorial as good as Hartl's book on how to do this in Rails. Presumably it would use Jquery and some other stuff maybe that I've not heard of to make the code not be a million lines?

  • 写回答

2条回答 默认 最新

  • python小菜 2012-09-11 23:16
    关注

    My best attempt at an answer is that it really depends on the scope and complexity of what you're trying to achieve. Generally, JSON shows up in views. If your application does not require you to dynamically retrieve JSON, that is, you can load it all when the view is initially rendered, then you can set an instance variable in your view's controller like so @my_json = some_object.to_json() Then, your instance variable is available in your view

        <script type = 'text/javascript'>
            var theJSON = <%= @my_json %>
        </script>
       

    Now, your data is available in the DOM, parsed nicely into JSON.

    If your application requires you to dynamically retrieve JSON after the controller/view are loaded, then you should probably look into using AJAX to hit a particular controller's method that returns the JSON that you desire.

    Here's a good RailsCast that can hopefully help you along your way Passing Data to Javascript

    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题