[英]parsing json string in ruby
我正在嘗試通過ajax調用解析來自控制器的json字符串。 解析的json字符串在js.erb文件中。 我設置了類似於以下堆棧溢出建議的代碼: 在Ruby中解析JSON字符串 。 我添加了gem,但是不是簡單地添加代碼,而是將<%%>放在代碼的紅寶石部分,因為它是js.erb文件而不是.rb文件。
我完整的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>
我怎樣才能使Ruby.parse的JSON.parse工作? 在JavaScript中,它工作正常。
您現在正在做的是:
require 'json'
JSON.parse('data') # which throws unexpected token at 'data' because JSON can't parse the string 'data'
如果您的目標只是將解析的json附加到dom元素,那么我看不到需要JSON並在ruby中進行處理嗎?
這個javascript應該做得很好(檢查此SO答案 ):
.done(function(data) {
$("#user_data").append(JSON.parse(data));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.