Reputation:
I am using jQuery to parse XML on my page using $.ajax()
. My code block is below and I can get this working to display say each result on the XML file, but I am having trouble because each section can have MORE THAN ONE <course>
and im trying to print ALL grades that belong to ONE STUDENT. Here is an example of the XML.
<student num="505">
<name gender="male">Al Einstein</name>
<course cid="1">60</course>
<course cid="2">60</course>
<course cid="3">40</course>
<course cid="4">55</course>
<comments>Lucky if he makes it to lab, hopeless.</comments>
</student>
Where you see the <course>
I am trying to get the results to print the grades for EACH student in each course. Any ideas on what I would do?
$.ajax({
type: "GET",
url: "final_exam.xml",
dataType: "xml",
success: function(xml) {
var student_list = $('#student-list');
$(xml).find('student').each(function(){
$(xml).find('course').each(function(){
gradeArray = $(this).text();
console.log(gradeArray);
});
var name = $(this).find("name").text();
var grade = $(this).find("course").text();
var cid = $(this).find("course").attr("cid");
//console.log(cid);
student_list.append("<tr><td>"+name+"</td><td>"+cid+"</td><td>"+grade+"</td></tr>");
});
}
});
Upvotes: 0
Views: 1334
Reputation: 9196
Pretty sure you are looking for this. All I did was capture grades in an array and join them via comma at the end. I also did not test (evil).
$.ajax({
type: "GET",
url: "final_exam.xml",
dataType: "xml",
success: function(xml) {
var student_list = $('#student-list');
$(xml).find("student").each(function(){
var name = $(this).find("name").text();
var grades = [];
var cid = $(this).find("course").attr("cid");
$(this).find('course').each(function(){
var grade = $(this).text();
console.log(gradeArray);
grades[ grades.length ] = grade
});
//console.log(cid);
student_list.append("<tr><td>"+name+"</td><td>"+cid+"</td><td>"+grades.join(', ')+"</td></tr>");
});
}
});
Upvotes: 0
Reputation: 19495
On this line: $(xml).find('course').each(function(){
Did you mean to find
off of xml
or should that be $(this).find
?
Upvotes: 1