我是使用ajax的新手(我本学期正在重新学习我的网络工程课程),我可以从服务器中提取文本文件并能够显示它。它在我的HTML页面上显示如下:
纽约8,143,197洛杉矶3,844,829芝加哥2,842,518 ......
但我希望它能在一列中显示城市,在另一列中显示人口。
我该怎么办?我还没有学过jquery。
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function loadXMLDoc() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
// Get which country the user selected
var radioArray = document.myForm.countries;
var i;
var value;
for (i = 0; i < radioArray.length; i++) {
if (radioArray[i].checked) {
value = radioArray[i].value;
}
}
if (value == "usa") {
xmlhttp.open("GET","http://localhost/~ercanbracks/usa.txt",true);
}
if (value == "canada") {
xmlhttp.open("GET","http://localhost/~ercanbracks/canada.txt",true);
}
if (value == "mexico") {
xmlhttp.open("GET","http://localhost/~ercanbracks/mexico.txt",true);
}
if (value == "russia") {
xmlhttp.open("GET","http://localhost/~ercanbracks/russia.txt",true);
}
xmlhttp.send();
}
</script>
</head>
<body onload="loadXMLDoc()">
<h1>Most populated cities in the world!</h1>
<form name="myForm" action="">
<input type="radio" name="countries"
onchange="loadXMLDoc()" value="usa" checked>USA
<br/>
<input type="radio" name="countries"
onchange="loadXMLDoc()" value="canada">Canada
<br/>
<input type="radio" name="countries"
onchange="loadXMLDoc()" value="mexico">Mexico
<br/>
<input type="radio" name="countries"
onchange="loadXMLDoc()" value="russia">Russia
</form>
<div id="myDiv"></div>
</body>
</html>
答案 0 :(得分:1)
无论响应是什么,您都会将整个响应文本分配给元素“myDiv”。您需要首先处理响应中的数据(xmlhttp.responseText) - 这样您可以分离城市 - 人口对,并根据您获得的对的行数,您可以创建一个新的表元素,并指定表的行和单元格。
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest();
else
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var dataToProcess = xmlhttp.responseText;
// process the data to get city-population pairs - assign them to an array for example
//...
// Create a new table element
var Table = document.createElement("Table");
// Foreach city-population pair, create one row and specify it's cells
for (var i = 0; i < YourArray.length; i++)
{
row = Table.insertRow(i);
cell1 = row.insertCell(0);
cell1.innerHTML = 'Your city value'; // YourArray[i]['City'];
cell2 = row.insertCell(1);
cell2.innerHTML = 'Your population value'; // YourArray[i]['Population'];
}
// Assign the table to a parent element
document.getElementById("your parent element").appendChild(Table);
// Be careful to which element you assign the new table element as a child, so that the page content don't need to be redrawn to make it visible
}
}
}