Rails 4:将JSON对象(来自AJAX响应)呈现到视图中 [英] Rails 4: Rendering JSON object (from AJAX response) into view

查看:81
本文介绍了Rails 4:将JSON对象(来自AJAX响应)呈现到视图中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Rails 4,并且对JSON对象还很陌生.

I'm using Rails 4 and I'm quite new to JSON objects.

我有一个控制器:

class UsersController < ApplicationController

 def select_users

   @users = User.all
   respond_to do |format|
     format.html
     format.js {} 
     format.json { 
        render json: {:users => @users}
     } 
   end
 end
end

还有一个javascript users.js:

And a javascript users.js:

$.ajax({
    url:  "/users/select_users",
    dataType: "json",
    data: {
        prezzario: ui.item.value
    },
    success: function(data) { 
        $('#usersList').append(data.users);
    }
});

现在,我想在div中呈现此用户集合,但是我不知道如何.在数据响应中,我在控制台中具有正确的数据,并带有如下所示的对象:

Now I want to render this collection of users in a div, but I don't know how. In the data response I have in the console the correct data, with an object like this:

{"users":[{"_id":{"$oid":"536cf7b6b8dd181f4b7acf9f"},"children":[{"$oid":"536cf7b6b8dd181f4b7acfa0"},{"$oid":"536cf7b7b8dd181f4b7acfd1"}],"description":"Some description.","name":"My name","user_id":"1"},{...........}]}

我有一个/users/_users.html.erb部分,其中包含经典的users.each和所有属性的打印件. 如果我尝试

I have a partial /users/_users.html.erb with classic users.each and prints of all properties. If I try

$('#usersList').append("<%= render 'users', :locals{ :users => "+data.users+"} %>");

我在div #usersList <%= render 'users', :locals{ :users => undefined }%>

我想创建部分模板并将其用于呈现用户.我该怎么办?

I want to create a partial template and use it to render users. How can I do this?

推荐答案

有3种解决方案(我能想到):

There are 3 solutions (that i can think of):

  1. 您的控制器可以在您附加到js的后端上呈现HTML,例如

  1. Your controller can render HTML on the backend that you append to your js, like

 class UsersController < ApplicationController

   def select_users
     @users = User.all
     render "view", :users => @users
   end

 success: function(data) {
   $('#usersList').append(data);
 }

  • 您可以使用诸如Moustache或Handlebars之类的东西.从未使用过它,所以我不能做一个正确的例子.抱歉.

  • You can use something like Moustache or Handlebars. Never used it, so I can't do a proper example. Sorry.

    您可以在侧面显示html之类的成功代码

    You can render the html in side the success code like

     success: function(data){
       data.users.forEach(function(user){
         $user_html = $("<div class='user'>" + user.name + "<!-- etc --!/></div>");
         $('#usersList').append($user_html);
       });
     });
    

  • 这篇关于Rails 4:将JSON对象(来自AJAX响应)呈现到视图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆