ajaxhe 2016-04-11
ajax.xml
<?xml version="1.0" encoding="UTF-8"?> <stulist> <student email="[email protected]"> <name>zhangsan</name> <id>1</id> </student> <student email="[email protected]"> <name>lisi</name> <id>2</id> </student> </stulist>
demo.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>加载XML</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="generator" content="editplus" /> <script type="text/javascript" src="js/jquery-1.10.1.min.js"></script> <script type="text/javascript"> $(function() { $("button").click(function(){ $.ajax({ url:'xml/ajax.xml', type: 'GET', dataType: 'xml', timeout: 1000, cache:false, error: function(xml){ alert('加载XML文档出错'); }, success: function(xml){ //建立一个代码片段 var frag=$("<ul/>"); //遍历所有student节点 $(xml).find("student").each(function(i){ //获取id节点 var id=$(this).children("id"), //获取节点文本 id_value=id.text(), //获取student下的email属性。 email=$(this).attr("email"); //构造HTML字符串,通过append方法添加进之前建立代码片段 frag.append("<li>"+id_value+"-"+email+"</li>"); }); //最后得到的frag添加进HTML文档中 frag.appendTo("#load"); } }); }); }); </script> </head> <body> <button>加载</button> <div id="load"></div> </body> </html>
效果图: