jquery ajax解析xml

js

$(document).ready(function () {
    $.ajax({
        type: 'POST',
        url: 'ajax_xml.xml',
        data: 'xml',
        success: function (data) {
		
			$(data).find("book").each(function(){
				sd="<ul class='cell'>"
				var book=$(this)
				var category=$(this).attr("category")
				var title=$(this).children("title").text()
				var author=$(this).children("author").text()
				var year=$(this).children("year").text()
				var price=$(this).children("price").text()
				sd+="<li>"+category+"</li>"+"<li>"+title+"</li>"+"<li>"+author+"</li>"+"<li>"+year+"<li>"+"<li>"+price+"</li>"
				sd+="<ul>"
				$("html body").append(sd)
				})
				
        }

    })
})

 css

ul{ list-style:none;}
 .cell{ float:left; }
 div{ float:left;}

 xml

<?xml version="1.0" encoding="utf-8"?>
<bookstore>
<book category="COOKING">
  <title lang="en">Everyday Italian</title> 
  <author>Giada De Laurentiis</author> 
  <year>2005</year> 
  <price>30.00</price> 
</book>
<book category="CHILDREN">
  <title lang="en">Harry Potter</title> 
  <author>J K. Rowling</author> 
  <year>2005</year> 
  <price>29.99</price> 
</book>
<book category="WEB">
  <title lang="en">Learning XML</title> 
  <author>Erik T. Ray</author> 
  <year>2003</year> 
  <price>39.95</price> 
</book>
</bookstore>

 js2结构修改

$(document).ready(function () {
    $.ajax({
        type: 'POST',
        url: 'ajax_xml.xml',
        data: 'xml',
        success: function (data) {
         var p="<div style=' border:1px solid red;'>";
            $(data).find("book").each(function(){
                var book=$(this)
                var category=$(this).attr("category")
                var title=$(this).children("title").text()
                var author=$(this).children("author").text()
                var year=$(this).children("year").text()
                var price=$(this).children("price").text()
				var sd="<ul class='cell'>"
                sd+="<li>"+category+"</li>"+"<li>"+title+"</li>"+"<li>"+author+"</li>"+"<li>"+year+"</li>"+"<li>"+price+"</li>"
				sd+="</ul>"
				p=p+sd
                })
			p+="</div>"	
          $("html body").html(p)       
        }
 
    })
})

 

posted @ 2012-04-18 10:51  break_happy  Views(328)  Comments(0)    收藏  举报