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'?
When I use data[name] => "undefined"
When I use data[lecture_name] => in console时
@lectures will have these columns: id, lecture_name, lecture_division, passfail, .. etc.
(there is no 'name' column)
HELP please
First of all, you´re not extracting the index inside the for loop. 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...
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.
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(). It's the complement of JSON.stringify().
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.