简体   繁体   中英

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

I implement the following code in my rails application.js file. When the user clicks on the link, the view reloads with a complete list of reviewers instead of the first 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. 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. Javascript is client side. You can't dynamically place ruby code into your website client side, as it needs to get run on the server first.

You'll have to create a rails script which runs this line

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

and then load it into your element by using load() eg:

$(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.

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.

show.html.erb:

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

application.js:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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