gpt4 book ai didi

javascript - 如何在rails中将json转换为html

转载 作者:行者123 更新时间:2023-12-03 09:46:49 26 4
gpt4 key购买 nike

我在读取网页上的 JSON 时遇到问题。我的网页由一堆圆圈组成,每次有人按下圆圈时,都会调用 Controller 来查询数据库并返回有关该特定圆圈的信息。这些信息以各种图表和文本信息的形式呈现。

Controller 返回 JSON,因为这是图表所需要的。不过我也想呈现文本信息。目前,文本信息以未格式化的 JSON 形式呈现,而我只想显示其中的某些部分

Controller :

def show
@user = User.find_by name: params[:name]
respond_to do |format|
# Here we need to remove the layout because the request
# is done via ajax and the layout is already loaded.
#format.html { render :layout => false }
format.json { render json: @user.to_json }
end

end

页面(未显示图表)

<ul>
<li id="Name">Name: <%= @user.name %></li>
<li id=Email>Email: <%= @user.email %></li>
<li id="id">Id: <%= @user.id %></li>
<li id="FBScore">Facebook Score: <%= @user.FBScore %></li>
<li id="PinterestScore">Pinterest Score: <%= @user.PinterestScore %></li>
<li id="InstagramScore">Instagram Score: <%= @user.InstagramScore %></li>
<li id="TwitterScore">Twitter Score: <%= @user.TwitterScore %></li>
<h1><li id="OverallScore">Overall Score:<%= @user.TwitterScore + @user.InstagramScore + @user.PinterestScore + @user.FBScore %></h1>
</ul>

当前结果:

Profile details
Score details
{"id":372,"name":"Voluptatem Quo Facilis","email":null,"created_at":"2015-06-22T10:46:59.827Z","updated_at":"2015-06-22T10:46:59.827Z","password_digest":null,"remember_digest":null,"admin":null,"activation_digest":null,"activated":null,"activated_at":null,"reset_digest":null,"reset_sent_at":null,"group":4,"FScore":27,"TScore":48,"IScore":94,"PScore":93}

我想要什么:

Profile details
Score details
id:372
name:Voluptatem Quo Facilis
email: null
FScore:27
TScore:48
IScore:94
PScore:93

所以我想问题取决于如何编写变量,以便提取我想要显示的 JSON 位?

最佳答案

如果我正确地解决了您的问题,那么您可以这样做:

 def show
@user = User.find_by name: params[:name]
respond_to do |format|
format.html { render :layout => false }
format.json { render json: @user.to_json }
end
end

现在新功能可以在 HTML 页面上显示用户详细信息:

<ul>
<li id="Name">Name: <%= @user.name %></li>
<li id=Email>Email: <%= @user.email %></li>
<li id="id">Id: <%= @user.id %></li>
</ul>

此外,在图表中,您需要传递 JSON 响应,以便您可以访问 JSON 响应,如下所示:假设您必须在图表中传递数据,因此只需这样做

 var data = "users/:id.json" #call your show action in json format

关于javascript - 如何在rails中将json转换为html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30998312/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com