I'm working on a Rails project in which I have a somewhat of an odd situation where I need to load a template (via ajax) into an existing page and populate the template with values from a Ruby array sent from that page. Here's my example:
Article Page:
<div class="article"></div>
<% @article = my_article_array.to_json %>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$.ajax({
type: 'post',
data: { 'article' : '<%= @article %> },
url: '/articles/show',
success: function(result) {
$(".article"开发者_StackOverflow社区).html(result);
}
});
});
</script>
Controller:
def show
@article = JSON.parse(params[:article])
redner :template => false
end
Template:
<h1><%= @article.title %></h1>
<p><%= @article.body %></p>
This results in a Rails error: "JSON.parse unexpected token error".
I've tried dozens of different scenarios, but converting the array to JSON first then decoding it once passed along seemed to make the most sense. Regardless, none of my attempts have worked.
Any insights would be much appreciated!
Using JSON to transport you data to the page and back again shouldn't be a problem. If your actual code is anywhere near as messy and buggy as your example then you likely just have a few bugs to squash and are on the right track.
精彩评论