我需要Ajax和jQuery的帮助。
我收到了来自Ajax调用的XML数据:
<data>
<book title=“Book1” bookID="1">
<AuthorsNum>3</AuthorsNum>
<author>
<authorId>1</authorId>
<fName> Mark </fName>
<mName>null</mName>
<lName>White</lName>
<education>PHD</education>
<role>Writer</role>
</author>
<author>
<authorId>2</authorId>
<fName>Jhon</fName>
<mName>null</mName>
<lName>Brown</lName>
<education>PHD</education>
<role>Writer</role>
</author>
</book>
<book title=“Book2” bookID=“2”>
<AuthorsNum>4</AuthorsNum>
<author>
<authorId>1</authorId>
<fName> Mark </fName>
<mName>null</mName>
<lName>White</lName>
<education>PHD</education>
<role>Writer</role>
</author>
</book>
我需要创建一个带有书名和ID的下拉菜单(选择)。然后,当选择每本书时,我需要显示作者姓名和教育。现在,我得到了下拉列表,但我无法弄清楚如何获得所选书籍并循环浏览本书的所有作者以显示它们。
这就是我所做的:
printAuthors = function(){
$.ajax({
type: "GET",
async: true,
cache: false,
url: url,
data: {path: "/mypath" },
dataType: "xml",
success: function(data, status){
var myContent = "";
if( $(data).find("error").length!=0){
}
else{
var selectElement = $("<select id='bookMenu' name='bookMenu' />");
var content="";
$( "book", data).each( function() {
$("<option />", {value: $(this).attr('bookID') , text: $(this).attr('title') }).appendTo(selectElement);
var selectedOption = this.value;
$( "author", $(data).find('book[bookID="' + selectedOption + '"]').children()).each( function() {
// get the name and education and append them to a #myDiv
});
});
$( "#myDiv").html( selectElement ) ;
}
}
});
}
有人可以帮忙吗?有没有更好的方法来实现菜单和结果?
答案 0 :(得分:0)
好的,这看起来很简单:
第二种方法:
答案 1 :(得分:0)
何时使用data-属性的完美示例,here是属性的另一个更简单的介绍。
$("book", data).each(function () {
//NOTE: this solution assumes names and edus are the same length. (every author has an education).
//add logic if not the case
var authors = "";
var authors_edu = "";
$(this).find('author').each(function () {
authors += $(this).find('fName').text() + " " + $(this).find('lName').text() + ", ";
authors_edu += $(this).find('education').text() + ", ";
});
//remove trailing comma
if (authors.lastIndexOf(",") == authors.length - 2) {
authors = authors.substr(0, authors.length - 2);
authors_edu = authors_edu.substr(0, authors_edu.length - 2);
}
selectElement.append($("<option>").attr('value', $(this).attr('bookID'))
.text($(this).attr('title'))
.attr('data-auth-name', authors)
.attr('data-auth-edu', authors_edu)
.on('click', function () {
var names = $(this).attr('data-auth-name').split(',');
var edus = $(this).attr('data-auth-edu').split(',');
$('#myTable > tbody').empty();
for (var i = 0; i < names.length; i++) {
$('#myTable > tbody:last-child').append('<tr><td>' + names[i] + '</td><td>' + edus[i] + '</td></tr>');
}
}));
var selectedOption = this.value;
});
HTML:
<div id="myDiv">
</div>
<div id="myDiv2">
<table id="myTable">
<thead><tr><th>Author Name</th><th>Education</th></tr></thead>
<tbody></tbody>
</table>
</div>
我已修改代码以满足评论中所述的“表格”要求。这个解决方案应该适合你的情况。
另一种选择是创建一个作者对象的全局列表并为其分配book_id,然后在“更改”选择列表中查找链接到该book_id的列表中的所有作者。