Ajax là cách viết tắt của Asynchronous Javascript And XML, do đó bây giờ chúng ta xem làm thể nào để xử lý một tài liệu XML.
Tập tin sandwiches.xml
<?xml version="1.0"?>
<sandwiches>
<sandwich>ham</sandwich>
<sandwich>turkey</sandwich>
<sandwich>cheese</sandwich>
</sandwiches>
Chúng ta có thể chỉ định kiểu dữ liệu xml trong hàm $.ajax() để lấy một đối tượng XML, cái mà đã làm rõ bằng cách gọi đến các hàm khác. Ví dụ chúng ta hiển thị các loại bánh sandwich trong selectbox
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="js/jquery-1.4.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$.ajax({
type: "GET",
url: "sandwiches.xml",
dataType: "xml",
success: callback
});
});
function callback(data, status)
{
var sandwiches = data.getElementsByTagName("sandwich");
listSandwiches(sandwiches);
}
function listSandwiches(sandwiches)
{
var loopIndex;
var selectControl = document.getElementById('sandwichList');
for (loopIndex = 0; loopIndex < sandwiches.length; loopIndex++)
{
selectControl.options[loopIndex] = new Option(sandwiches[loopIndex].firstChild.data);
}
}
function err(xhr, reason, ex)
{
$("div").text(reason);
}
</script>
</head>
<body>
<h1>Using $.ajax( ) to get XML</h1>
<form>
<select size="1" id="sandwichList">
<option>Select a sandwich</option>
</select>
</form>
</body>
</html>
(Nguồn: ZendVN group - www.zend.vn)
Không có nhận xét nào:
Đăng nhận xét