0
我編寫了一個代碼,它從Harvard Uni生成XML文件並將其放入下拉列表中,接下來您可以從列表中選擇一個課程,它將生成一個包含課程詳細信息的表格。嘗試使用Ajax處理XML
<script type="text/javascript" src="Script/jquery-1.7.2.js"></script>
<script type="text/javascript">
$('#button').click(function() {
document.getElementById("span").style.visibility = "visible";
document.getElementById("button").style.visibility = "hidden";
$.ajax({
type: "GET",
url: "Harvard.aspx?field=COMPSCI",
success: function (data) {
var courses = data.documentElement.getElementsByTagName("Course");
var options = document.createElement("select");
$(options).change(function() {
ShowCourseDetails(this);
});
for (var i = 0; i < courses.length; i++) {
var option = document.createElement("option");
option.value = $(courses[i]).find("cat_num").text();
option.text = $(courses[i]).find("title").text();
options.add(option, null);
}
document.getElementById("selectDiv").appendChild(options);
document.getElementById("span").style.visibility = "hidden";
}
});
});
function ShowCourseDetails(event) {
// get the index of the selected option
var idx = event.selectedIndex;
// get the value of the selected option
var cat_num = event.options[idx].value;
$.ajax({
type: "GET",
url: "http://courses.cs50.net/api/1.0/courses?output=xml&&cat_num=" + cat_num,
success: function (data) {
$("#TableDiv").html(ConvertToTable(data.documentElement));
}
});
}
function ConvertToTable(targetNode) {
targetNode = targetNode.childNodes[0];
// first we need to create headers
var columnCount = 2;
var rowCount = targetNode.childNodes.length
// name for the table
var myTable = document.createElement("table");
for (var i = 0; i < rowCount; i++) {
var newRow = myTable.insertRow();
var firstCell = newRow.insertCell();
firstCell.innerHTML = targetNode.childNodes[i].nodeName;
var secondCell = newRow.insertCell();
secondCell.innerHTML = targetNode.childNodes[i].text;
}
// i prefer to send it as string instead of a table object
return myTable.outerHTML;
}
</script>
和身體:
<div id="main">
<div class="left">
<input id="button" type="button" value="Get all science courses from HARVARD"/>
<br />
<span id="span" style="visibility: hidden">Downloading courses from harvard....</span>
<div id="selectDiv"></div>
<div id="TableDiv"></div>
</div>
</div>
和我所得到的下拉僅在下拉列表中所有行「不確定」,可有人可以看到我寫的代碼問題?
10X很多提前:)
感謝您的幫助!我改變了你所提到的所有內容,但它仍停留在「從哈佛下載課程...」,甚至沒有顯示下拉列表:\ \無限循環也許:\ – SigmaOmega 2012-07-18 18:31:33
嘗試將您的jQuery升級到最新版本。另外,發佈您的更新代碼。 – Tim 2012-07-18 18:59:04
我升級了jQuery仍然沒有結果。你可以在我編輯的帖子中看到我的更新代碼。 – SigmaOmega 2012-07-18 19:15:53