Ajax动态创建表单内容

这个例子展示了如何使用W3C DOM和JavaScript来动态创建内容。这个例子是假想的房地产清单搜索引擎,点击表单上的Search按钮,会使用XMLHttpRequest对象以XML格式获取结果。使用JavaScript处理响应XML,从而生成一个表,其中列出索到的结果。
服务器返回的XML,根节点properties包含了得到的所有property元素。每个property元素包含3个子元素:address、price和comments.
dynamicContent.xml代码如下:

<?xml version="1.0" encoding="utf-8"?>
<properties>
 <property>
  <address>812 Gwyn Ave</address>
  <price>$100,000</price>
  <comments>Quiet,serene neighborhood</comments>
 </property>
 <property>
  <address>3308 James Ave S</address>
  <price>$110,000</price>
  <comments>close to schools,shopping,entertainment</comments>
 </property>
 <property>
  <address>98300 County Rd 113</address>
  <price>$115,000</price>
  <comments>Small acreage outside of town</comments>
 </property>
</properties>

具体向 服务器发送请求并对服务器响应做出回应的JavaScript与前面的例子是一样的。不过,从handleReadyStateChange函数开始有所不同。假设请求成功地完成,接下来第一件事就是调用clearPreviousResults函数,将以前搜索所创建的内容删除。
 clearPreviousResults函数完成两个任务:删除出现在最上面的“Results“标题文本,并从结果表中清除所有行。首先使用hasChikdNodes方法查看可能包括标题文本的span元素是否有子元素。应该知道,只有hasChildNodes方法返回true时才存在标题文本。如果确实返回true,则删除span元素的第一个(也是惟一的)子节点,因为这个子节点表示的就是标题文本。
 clearPreviousResults的下一个任务是在显示搜索结果的表中删除所有行。所有结果行都是tbody节点的子节点,所以先使用document.getElementById方法得到该tbody节点的引用。一旦有了tbody节点,只要这个tbody节点还有子节点(tr元素)就进行迭代处理。每次迭代时都 会从表体中删除childNodes集合中的第一个子节点。当表体中再没有更多的表行时,迭代结束。
搜索结果表在parseResults函数中建立函数中建立。这个函数首先创建一个名为results的局部普通量,这是使用XMLHttpRequest对象的responseXML属性得到的XML文档。
  使用getElementsByTagName方法来获得XML文档中包含所有property元素的数组,然后将这个数组赋给局部变量properties。一旦有了property元素的数组,可以迭代处理数组中的各个元素,并获得property的address、price和comments.
var properties = results.getElementsByTagName("property");
   for(var i=0;i<properties.length;i++){
     property = properties[i];
     address = property.getElementsByTagName("address")[0].firstChild.nodeValue;
     price = property.getElementsByTagName("price")[0].firstChild.nodeValue;
     comments = property.getElementsByTagName("comments")[0].firstChild.nodeValue;
     addTableRow(address,price,comments);
    }
下面仔细分析这个循环,因为这正是parseResults函数的核心。在for循环中,首先得到数组中的下一个元素,并把它赋给局部变量property。接下来,对于你感兴趣的各个子元素,分别获得它们的节点值。
 请考虑address元素,这是property元素的一个子元素。首先在property元素上调用getElementsByTagName方法来得到单address元素。getElementsByTagName方法返回一个数组,不过因为知道有且仅有一个address元素,所以可以使用[0]记法来引用这个元素。
   沿着XML结构继续向下,现在有了address标记的引用,需要得到它的文本内容。记住,文本实际上是父元素的一个子节点,所以可以使用firstChild属性来访部address元素的文本节点。有了文本节点后,可以引用文本节点的nodeValue属性来得到文本。
   采用同样的方法来得到price和comments元素的值,并把各个值分别赋给局部变量price和comments。再将address、price和comments传递给名为addTableRow的辅助函数,它会用这些结果数据具体建立一个表行。
   addTableRow函数使用W3C DOM方法和JavaScript建立一个表行。使用document.createElement方法创建一个row对象,之后,再使用名为createCellWithText的辅助函数分别为address、price和comments值创建一个cell对象。createCellWithText函数会创建并返回一个指定的文本作为单元格内容的cell对象。
   createCellWithText函数首先使用document.createElement方法创建一个td元素,然后使用document.createTextNode方法创建一个包含所需文本的文本节点,所得到的文本节点追加到td元素。这个函数再把建的td元素返回给调用函数(addTableRow)。
   addTableRow函数对addrss、price和comments值重复调用createCellWithText函数,每一次向tr元素追加一个新创建的td元素。一旦向row增加了所有cell(单元格),这个row就将被增加到表的tbody元素中。
下面是完整的javascript和html代码:jsp文件

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
 String path = request.getContextPath();
 String basePath = request.getScheme() + "://"
   + request.getServerName() + ":" + request.getServerPort()
   + path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
  <base href="<%=basePath%>">

  <title>My JSP 'index.jsp' starting page</title>
  <meta http-equiv="pragma" content="no-cache">
  <meta http-equiv="cache-control" content="no-cache">
  <meta http-equiv="expires" content="0">
  <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  <meta http-equiv="description" content="This is my page">
  <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->
  <script language="javascript" type="text/javascript">
 var XMLrequest = false;
 try {
  XMLrequest = new XMLHttpRequest();
 } catch (trymicrosoft) {
  try {
   XMLrequest = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (othermicrosoft) {
   try {
    XMLrequest = new ActiveXObject("Microsoft.XMLHTTP");
   } catch (failed) {
    XMLrequest = false;
   }
  }
 }
 if (!XMLrequest) {
  alert("Error initializing XMLHttpRequest!");
 }
 function doSearch() {
  var url = "<%=basePath%>/dongtai/dynaimcContent.xml";
  XMLrequest.open("GET", url, true);
  XMLrequest.onreadystatechange = updatePage;
  XMLrequest.send(null);
 }
 function updatePage() {
  if (XMLrequest.readyState == 4) {
   if (XMLrequest.status == 200) {
    clearPreviousResults();
    parseResults();
   }
  }
 }
 function clearPreviousResults(){
   var header = document.getElementById("header");
   if(header.hasChildNodes()){
     header.removeChild(header.childNodes[0]);
    }
   var tableBody = document.getElementById("resultsBody");
   while(tableBody.childNodes.length>0){
     tableBody.removeChild(tableBody.childNodes[0]);
    }
  }
 function parseResults(){
   var results = XMLrequest.responseXML;
   
   var property = null;
   var address = "";
   var price = "";
   var comments = "";
   var properties = results.getElementsByTagName("property");
   for(var i=0;i<properties.length;i++){
     property = properties[i];
     address = property.getElementsByTagName("address")[0].firstChild.nodeValue;
     price = property.getElementsByTagName("price")[0].firstChild.nodeValue;
     comments = property.getElementsByTagName("comments")[0].firstChild.nodeValue;
     addTableRow(address,price,comments);
    }
   var header = document.createElement("h2");
   var headerText = document.createTextNode("Results:");
   header.appendChild(headerText);
   document.getElementById("header").appendChild(header);
   document.getElementById("resultsTable").setAttribute("border","1");
  }
 function addTableRow(address,price,comments){
   var row = document.createElement("tr");
   var cell = createCellWithText(address);
   row.appendChild(cell);
   cell = createCellWithText(price);
   row.appendChild(cell);
   cell = createCellWithText(comments);
   row.appendChild(cell);
   document.getElementById("resultsBody").appendChild(row);
  }
 function createCellWithText(text){
  //alert(address);
   var cell = document.createElement("td");
   var textNode = document.createTextNode(text);
   cell.appendChild(textNode);
   return cell;
  }
</script>
 </head>
 <body>
  <h1>Search Real Estate Listings</h1>
  <form action="#">
   <select>
    <option value="50000">$50,000</option>
    <option value="100000">$100,000</option>
    <option value="150000">$150,000</option>
   </select>
   to
   <select>
    <option value="100000">$100,000</option>
    <option value="150000">$150,000</option>
    <option value="200000">$200,000</option>
   </select>
   <input type="button" value="Search" οnclick="doSearch();" />
  </form>
  <span id="header"></span>
  <table id="resultsTable" width="75%" border="0">
   <tbody id="resultsBody">
    
   </tbody>
  </table>
 </body>
</html>

转载于:https://www.cnblogs.com/xingzhen/archive/2011/06/01/2067169.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值