Việc sử dụng ajax để nạp dữ liệu động trong trang web được ứng dụng rất phổ biến. Các dữ liệu này thương được lưu trong các tập tin XML và được nạp bằng đối tượng XMLHttpRequest. Tuy nhiên, bạn cũng có thể sử dụng ajax trong jQuery để làm điều này. Trong bài viết này, tôi sẽ giới thiệu cách nạp một XML DOM bằng jQuery và hiển thị các dữ liệu trong đó lên một drop down list (select).
————-
Bài viết này sử dụng tập tin books.xml trên MSDN để làm ví dụ. Tập tin này có nội dung theo dạng sau:
<?xml version=”1.0″?> <catalog> <book id=”bk101″> <author>Gambardella, Matthew</author> <title>XML Developer’s Guide</title> <genre>Computer</genre> <price>44.95</price> <publish_date>2000-10-01</publish_date> <description>An in-depth look at creating applications with XML.</description> </book> <book id=”bk102″> <author>Ralls, Kim</author> <title>Midnight Rain</title> <genre>Fantasy</genre> <price>5.95</price> <publish_date>2000-12-16</publish_date> <description>A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.</description> </book> <book id=”bk103″> <author>Corets, Eva</author> <title>Maeve Ascendant</title> <genre>Fantasy</genre> <price>5.95</price> <publish_date>2000-11-17</publish_date> <description>After the collapse of a nanotechnology society in England, the young survivors lay the foundation for a new society.</description> </book> <book id=”bk104″> <author>Corets, Eva</author> <title>Oberon’s Legacy</title> <genre>Fantasy</genre> <price>5.95</price> <publish_date>2001-03-10</publish_date> <description>In post-apocalypse England, the mysterious agent known only as Oberon helps to create a new life for the inhabitants of London. Sequel to Maeve Ascendant.</description> </book> <book id=”bk105″> <author>Corets, Eva</author> <title>The Sundered Grail</title> <genre>Fantasy</genre> <price>5.95</price> <publish_date>2001-09-10</publish_date> <description>The two daughters of Maeve, half-sisters, battle one another for control of England. Sequel to Oberon’s Legacy.</description> </book> <book id=”bk106″> <author>Randall, Cynthia</author> <title>Lover Birds</title> <genre>Romance</genre> <price>4.95</price> <publish_date>2000-09-02</publish_date> <description>When Carla meets Paul at an ornithology conference, tempers fly as feathers get ruffled.</description> </book> <book id=”bk107″> <author>Thurman, Paula</author> <title>Splish Splash</title> <genre>Romance</genre> <price>4.95</price> <publish_date>2000-11-02</publish_date> <description>A deep sea diver finds true love twenty thousand leagues beneath the sea.</description> </book> <book id=”bk108″> <author>Knorr, Stefan</author> <title>Creepy Crawlies</title> <genre>Horror</genre> <price>4.95</price> <publish_date>2000-12-06</publish_date> <description>An anthology of horror stories about roaches, centipedes, scorpions and other insects.</description> </book> <book id=”bk109″> <author>Kress, Peter</author> <title>Paradox Lost</title> <genre>Science Fiction</genre> <price>6.95</price> <publish_date>2000-11-02</publish_date> <description>After an inadvertant trip through a Heisenberg Uncertainty Device, James Salway discovers the problems of being quantum.</description> </book> <book id=”bk110″> <author>O’Brien, Tim</author> <title>Microsoft .NET: The Programming Bible</title> <genre>Computer</genre> <price>36.95</price> <publish_date>2000-12-09</publish_date> <description>Microsoft’s .NET initiative is explored in detail in this deep programmer’s reference.</description> </book> <book id=”bk111″> <author>O’Brien, Tim</author> <title>MSXML3: A Comprehensive Guide</title> <genre>Computer</genre> <price>36.95</price> <publish_date>2000-12-01</publish_date> <description>The Microsoft MSXML3 parser is covered in detail, with attention to XML DOM interfaces, XSLT processing, SAX and more.</description> </book> <book id=”bk112″> <author>Galos, Mike</author> <title>Visual Studio 7: A Comprehensive Guide</title> <genre>Computer</genre> <price>49.95</price> <publish_date>2001-04-16</publish_date> <description>Microsoft Visual Studio 7 is explored in depth, looking at how Visual Basic, Visual C++, C#, and ASP+ are integrated into a comprehensive development environment.</description> </book> </catalog>
Cụ thể tôi sẽ lấy thẻ <title> của mỗi <book> để hiển thị trong drop down list. Khi người dùng chọn một mục cụ thể, thông tin về book đó sẽ được hiển thị chi tiết bên dưới.
Nạp tập tin XML
jQuery cung cấp một số hàm để làm việc với Ajax, và cách tổng quát nhất, cho phép sử dụng ajax ở mức thấp là hàm jQuery.ajax() . Bạn có thể truyền vào hàm này một hàm callback để thực hiện các công việc cần thiết. Hàm callback sẽ tự động được gọi sau khi dữ liệu được nạp hoàn tất.
Chẳng hạn như tôi muốn tạo ra các phần tử của một drop down list với dữ liệu từ tập tin books.xml:
$.ajax({ type: “GET”, url: “books.xml”, dataType: “xml”, success:function(xml) { // populate a drop down list } });
Tuy nhiên, thay vì làm cách này, tôi sẽ tạo một hàm dùng để nạp tập tin xml và trả về đối tượng XML DOM để có thể thao tác nhiều lần trên đối tượng này.
Hàm jQuery.ajax() trên có kiểu trả về là một đối tượng jqXHR (jQuery XMLHttpRequest). Bạn có thể lấy được kết quả XML trả về thông qua thuộc tính responseXML của đối tượng này. Tuy nhiên hãy đảm bảo rằng hàm jQuery.ajax() chỉ trả về kết quả sau khi thực hiện xong việc nạp dữ liệu bằng cách đặt tham số async là false (nạp dữ liệu đồng bộ, giá trị mặc định của tham số này là true):
function loadXmlDoc() { return $.ajax({ type: “GET”, url: “books.xml”, dataType: “xml”, async:false }).responseXML; }
Tạo các phần tử của drop down list
Trong tài liệu html của tôi có một thẻ <select> với id là bookSelect. Các bước để thêm tiêu đề của mỗi <book> trong đối tượng XML DOM vào phần tử <select> là:
– Dùng find() để tìm các thẻ <book> trong đối tượng XML DOM.
– Dùng each() để duyệt qua các phần tử <book>.
– Dùng append() để chèn các phần tử <option> vào trong phần tử <select>.
var xmlDoc=loadXmlDoc();
var xmlDoc=loadXmlDoc(); var select=$(“#bookSelect”); $(xmlDoc).find(“book”).each(function() { var title=$(this).find(“title”).text(); var id=$(this).attr(“id”); select.append(“<option value='”+id+”‘>”+title+”</option>”); });
Hiển thị thông tin của phần tử được chọn
Tôi sẽ hiển thị các thông tin của sách trong một danh sách <ul> với id là infoList:
Các bước thực hiện:
– Thêm hàm xử lý cho sự kiện change của drop down list.
– Xóa toàn bộ nội dung của phần tử <ul> bằng hàm html(“”).
– Lấy phần tử <book> trong XML DOM dựa vào giá trị của phần tử <option> được chọn.
– Chèn các thông tin sách vào <ul>, bao gồm các phần tử con của phần tử <book>.
var ul=$(“#detailList”); select.change(function() { ul.html(“”); var book=$(“book[id='”+this.value+”‘]”,xmlDoc); ul.append(“<li><b>id</b>=”+book.attr(“id”)+”</li>”); book.children().each(function() { var li=”<li><b>”+this.nodeName+”</b>=”+$(this).text()+”</li>”; ul.append(li); }); });
Mã trang html hoàn chỉnh
<html> <head> <script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js” type=”text/javascript”> </script> <script type=”text/javascript”> function loadXmlDoc() { return $.ajax({ type: “GET”, url: “books.xml”, dataType: “xml”, async:false }).responseXML; } $(function() { var xmlDoc=loadXmlDoc(); var select=$(“#bookSelect”); $(xmlDoc).find(“book”).each(function() { var title=$(this).find(“title”).text(); var id=$(this).attr(“id”); select.append(“<option value='”+id+”‘>”+title+”</option>”); }); var ul=$(“#infoList”); select.change(function() { ul.html(“”); var book=$(“book[id='”+this.value+”‘]”,xmlDoc); ul.append(“<li><b>id</b>=”+book.attr(“id”)+”</li>”); book.children().each(function() { var li=”<li><b>”+this.nodeName+”</b>=”+$(this).text()+”</li>”; ul.append(li); }); }); }); </script> </head> <body> Title: <select id=”bookSelect” style=”width:200px”></select> <p> Details: </p> <div style=”width:500px; height:250px; border:1px solid black”> <ul id=”infoList”></ul> </div> </body> </html>
Lưu ý:
Với Google Chrome: Trình duyệt này mặc định ko cho phép truy xuất các tập tin cục bộ, nên khi xem ví dụ này trong Google Chrome, bạn cần chạy Chrome với tham số sau:
-allow-file-access-from-files
https://yinyangit.wordpress.com