2014-09-23 177 views
0

我想通过ajax调用解析来自我的控制器的json字符串。被解析的json字符串位于js.erb文件中。我将代码设置为类似于堆栈溢出的建议:Parsing a JSON string in Ruby。我添加了宝石,但不是简单地添加代码,我不得不将<%%>放在代码的ruby部分,因为它是一个js.erb文件而不是.rb文件在ruby中解析json字符串

我的完整js.erb文件看起来像这样:

<% require 'json' %> 

$(document).ready(function() 
{ 


$('#collaboration_user_name').on('keyup', function() { 

    text = $(this).val(); 
    // alert(text); 

    $.ajax({ url: "/collaborations?collaboration="+text, 
    beforeSend: function(xhr) { 
     xhr.overrideMimeType("text/plain; charset=x-user-defined"); 
    } 
    }).done(function(data) { 
    console.log("data:", data); 
    users = JSON.parse(data); 

    $("#user_data ul li").remove(); 
    $.each(users, function(index, value) { 
     $("#user_data ul").append("<li role='presentation'>"+"<a role='menuitem' tabindex='-1' href='#'>"+users[index].name+ ", " +users[index].email+"</a>"+"</li>"); 
    }); 
    <% @user = "data" %>; 
    $("#user_data").append(<%= JSON.parse @user %>); 
}); 

}); 
}); 

需要注意的代码是

<% require 'json' %> 

在顶部和

<% @user = "data" %>; 
$("#user_data").append(<%= JSON.parse @user %>); 

位于页面的底部。当我添加这些行时,出现错误。

JSON::ParserError in Wikis#edit 
Showing /Users/warren/code/knowledgebank/app/views/layouts/application.html.erb where line #7   raised: 

757: unexpected token at 'data' 
    (in /Users/warren/code/knowledgebank/app/assets/javascripts/collaborations.js.erb) 
    Extracted source (around line #7): 

4<title>Knowledgebank</title> 
5<%= stylesheet_link_tag "application", media: "all" %> 
6 
7<%= javascript_include_tag 'application'%> 
8<%= csrf_meta_tags %> 
9</head> 
10<body> 

如何让JSON.parse for ruby​​工作?在JavaScript中它工作正常。

+0

' “数据”'无效'JSON'。 – 2014-09-23 04:04:24

回答

0

什么你现在正在做的是:

require 'json' 

JSON.parse('data') # which throws unexpected token at 'data' because JSON can't parse the string 'data' 

如果你的目标很简单,就是追加解析JSON DOM元素,然后我看不出有必要要求JSON和做,在红宝石?

这个JavaScript应该做的罚款(检查这个SO answer):

.done(function(data) { 
    $("#user_data").append(JSON.parse(data)); 
} 
+0

我需要它在红宝石,因为我想添加ruby的link_to方法来传递信息从点击时,从JSON对象返回到控制器。 – user3266824 2014-09-23 12:16:51