[英]ruby on rails - how to read json file using ajax?
I'm using these codes,我正在使用这些代码,
#In timetable/new.html.erb
<%= select_tag :department, options_for_select(
@departments.collect{ |d| [d.department_name, d.id]}, nil),{ id: "department_select" } %>
#In timetable controller
def update_lectures
if params[:department].to_i == 0
@lectures = Department.find_by(department_name: params[:department]).l ectures
else
@lectures = Department.find(params[:department]).lectures
end
respond_to do |format|
format.json { render :json => @lectures.to_json }
end
#In javascript
$("#department_select").change( function() {
$.ajax({
url: window.location.origin + '/timetable/update_lectures',
dataType: "json",
data: $("#department_select").serialize(),
success: function(data){
var str = '';
for(var i = 0; i < data.length; i++) {
str += '<li>' + data[name] + '</li>';
}
$('#lecture-container-body').html(str);
}
});
});
I want to know in #In javascript how can I read the 'data'?我想在#In javascript 中知道如何读取“数据”?
When I use data[name] => "undefined"当我使用 data[name] => "undefined"
When I use data[lecture_name] => "Uncaught ReferenceError: lecture_name is not defined" in console
当我在控制台中使用 data[lecture_name] => "Uncaught ReferenceError: talk_name is not defined"时
@lectures will have these columns: id, lecture_name, lecture_division, passfail, .. etc. @lectures 将有这些列:id、lecture_name、lecture_division、passfail 等。
(there is no 'name' column) (没有“姓名”栏)
HELP please请帮忙
First of all, you´re not extracting the index inside the for loop.首先,您不是在 for 循环中提取索引。 So, the array doesn´t have the props you need.
所以,数组没有你需要的道具。
In javascript you can access dynamically props using the brackets notation as you intended, but the property itself must be a String or a reference to a "string like" value...在javascript中,您可以按预期使用括号表示法动态访问道具,但属性本身必须是字符串或对“类似字符串”值的引用...
str += '<li>' + data[i]['name'] + '</li>'; //note the quotes in name!
is the same of doing是一样的做
str += '<li>' + data[i].name + '</li>';
So, when you´re doing所以,当你在做
str += '<li>' + data[last_name] + '</li>';
the interpreter looks for a variable named last_name
which throws the error you mentioned.解释器查找名为
last_name
的变量,该变量会引发您提到的错误。
In your success callback try:在您的成功回调中尝试:
success: function(data){
var str = '';
for(var i = 0; i < data.length; i++) {
str += '<li>' + JSON.parse(data).lecture_name + '</li>';
}
$('#lecture-container-body').html(str);
}
The voodoo you need is JSON.parse().您需要的巫毒是 JSON.parse()。 It's the complement of JSON.stringify().
它是 JSON.stringify() 的补充。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.