简体   繁体   English

Jquery.html显示文字代码,而不是在application.js中呈现html

[英]Jquery.html showing literal code instead of rendering html in application.js

I implement the following code in my rails application.js file. 我在rails application.js文件中实现以下代码。 When the user clicks on the link, the view reloads with a complete list of reviewers instead of the first 4: 当用户单击链接时,视图将重新加载完整的审阅者列表,而不是前4个:

$(document).ready(function(){
    $("#more_reviewers").click(function(e){
        $("#reviewer_list").html('<%= escape_javascript(render "restaurants/restaurant_reviewer_list", :venue => @restaurant, :limit => @restaurant.reviews.count) %>');
    });
});

Problem: instead of showing me the list, the code returns the Rails code as text. 问题:代码没有向我显示列表,而是以文本形式返回了Rails代码。 So on my screen, instead of seeing a list of users, I see: 因此,在屏幕上,我没有看到用户列表,而是看到:

'<%= escape_javascript(render "restaurants/restaurant_reviewer_list", :venue => @restaurant, :limit => @restaurant.reviews.count) %>'

This is probably going to be a simple one - and I'll appreciate it. 这可能会很简单-我会很感激的。

Rails is a server side programming language. Rails是服务器端编程语言。 Javascript is client side. Javascript是客户端。 You can't dynamically place ruby code into your website client side, as it needs to get run on the server first. 您无法将ruby代码动态地放入网站客户端,因为它需要首先在服务器上运行。

You'll have to create a rails script which runs this line 您必须创建运行此行的Rails脚本

<%= escape_javascript(render "restaurants/restaurant_reviewer_list", :venue => @restaurant, :limit => @restaurant.reviews.count) %>

and then load it into your element by using load() eg: 然后使用load()将其加载到您的元素中,例如:

$(document).ready(function(){
    $("#more_reviewers").click(function(e){
        $("#reviewer_list").load('http://url.to/the/script/you/made');
    });
});

That way the server gets sent a request for your script, it runs the script (server side) and delivers the output (html) to the javascript (client side) where it can be rendered. 这样,服务器将收到您的脚本请求,它运行脚本(服务器端),并将输出(html)传递到javascript(客户端),可以在其中进行呈现。

In addition to Thomas' explanation about client-side and server-side and assuming you don't have to make another request to the server: the easiest would be to just put the partial in a hidden div in your view and then use jQuery to display it. 除了托马斯的有关客户端和服务器端和假设的解释,你不必再拍请求到服务器:最简单的是只把部分的DIV隐藏在你的视图,然后使用jQuery显示它。

show.html.erb: show.html.erb:

<div style="display:none;" id="hidden_div">
  <%= render "restaurants/restaurant_reviewer_list", :venue => @restaurant, :limit => @restaurant.reviews.count %>
</div>

application.js: application.js:

$(document).ready(function(){
  $("#more_reviewers").click(function(e){
    $("#hidden_div").show();
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM