Danh mục

Thứ Bảy, 16 tháng 10, 2010

jQuery - ajax

jQuery ajax giúp chúng ta đơn giản hóa quá trình thực thi. Sau đây là một vài minh họa về tính tiện dụng của JQuery ajax.

Cú pháp

jQuery.ajax({
type:"POST", //Phương thức gửi request là POST hoặc GET
data:"id=12&name=abc", //tham số gửi kèm
dataType:"xml", //kiểu dữ liệu trả về, mặc định là text
url:"/login/servletLogin", //Đường dẫn tới nơi xử lý request ajax
success: function (){ //hàm gọi về khi thực hiện thành công
// mã lệnh
}
});

Ví dụ 1: Sử dụng HTML tạo một ví dụ đơn giản với jQuery ajax

  • Tạo một thư mục(ở đây tạm gọi là thư mục VD).
  • Vào thư mục VD tạo một file index.html có nội dung như sau
  • <html>
    <head>
     <script src="http://code.jquery.com/jquery-1.4.2.js"></script>
     <script type="text/javascript">
      jQuery(document).ready(function(){
       jQuery("#ajaxButton").click(function(){
        jQuery.ajax({
         type:"POST",
         url:"ajax.html",
         success:function(html){
          jQuery("#responseDiv").html(html);
         }
        });
       });
      });
     </script>
    </head>
    <body>
     <div>
      <input type="button" value="ajax" id="ajaxButton"/>
     </div>
     <div id="responseDiv">
     
     </div>
    </body>
    </html>

  • Tiếp tục tạo file ajax.html có nội dung như sau
  • <style>
    #sampleTable{
     border-collapse:collapse;
    }
    #sampleTable td{
     border: 1px solid black;
     width:100px;
    }
    </style>
    <table id="sampleTable">
     <tr>
      <td>Name</td>
      <td>Year</td>
     </tr>
     <tr>
      <td>Van A</td>
      <td>1982</td>
     </tr>
    </table>

  • Mở file index.html bằng trình duyệt bất kỳ click vào button ajax bạn sẽ thấy toàn bộ nội dung của file ajax.html được lấy về trang index.html.

Ví dụ 2: Dùng PHP tạo một ví dụ đơn giản với jQuery ajax.

  • Cài đặt ứng dụng chạy apache như Xampp hoặc Wamp. Start ứng dụng.
  • Tạo thư mục với tên là sample trong(thư mục htdocs đối với Xampp và www đối với Wamp)
  • Trong thư mục sample tạo file index.php có nội dung như sau:
  • <html>
    <head>
     <script src="http://code.jquery.com/jquery-1.4.2.js"></script>
     <script type="text/javascript">
      jQuery(document).ready(function(){
       jQuery("#ajaxButton").click(function(){
        jQuery.ajax({
         type:"POST",
         url:"ajax.php", //goi toi file ajax.php
         data:"name="+jQuery("#name").val()+"&year="+jQuery("#year").val(),//du lieu gui di
         success:function(html){
          jQuery("#responseDiv").html(html);
         }
        });
       });
      });
     </script>
    </head>
    <body>
     <table>
      <tr>
       <td>Name:</td>
       <td><input type="text" id="name"/></td>
      </tr>
      <tr>
       <td>Year:</td>
       <td><input type="text" id="year"/></td>
      </tr>
     </table>
     <div>
      <input type="button" value="ajax" id="ajaxButton"/>
     </div>
     <div id="responseDiv">
     </div>
    </body>
    </html>

  • Tạo tiếp file ajax.php trong thư mục sampe với nội dung như sau
  • <?php
     $name = $_REQUEST['name'];//Lay parameter tu request
     $year = $_REQUEST['year'];//Lay parameter tu request
     
     echo "<div>".$name." sinh nam ".$year."</div>";//Noi dung tra ve
    ?>

  • Bây giờ bạn mở một trình duyệt web lên(IE hoặc firefox) lên gõ vào thanh địa chỉ như sau: localhost/sample/
  • Bạn điền vào hai field Name và Year nhấn button ajax bạn sẽ thấy câu chào giống như hình dưới.

Thứ Tư, 22 tháng 9, 2010

jQuery - empty và remove

empty và remove thường được dùng để xóa các phần tử trong jQuery. Tuy hai hàm này có cùng chung một hành động nhưng chúng có một chút khác biệt như sau:

  • empty chỉ xóa các phần tử con của phần tử đang truy xuất.
  • remove giống hàm empty nhưng bao gồm cả phần tử đang truy xuất và phần tử con.
Ví dụ ta có một thẻ ul như sau:
<ul id="test_ul">
<li>lorem isum1</li>
<li class="current">lorem isum2</li>
<li>lorem isum3</li>
<li>lorem isum4</li>
</ul>
Khi ta sử dụng:
  • jQuery("#test_ul").empty() jQuery sẽ xóa toàn bộ nội dung của thẻ ul có id là test_ul nhưng vẫn giữ lại bản thân thẻ đó.
  • <ul id="test_ul">
    </ul>
  • jQuery("#test_ul").remove() jQuery sẽ xóa toàn bộ nội dung của thẻ ul có id là test_ul và xóa luôn cả thẻ ul test_ul. Tuy nhiên hàm remove sẽ trả về đối tượng mà nó vừa remove để chúng ta có khả năng lưu trữ và khôi phục lại khi cần
Demo ta có ô vuông bên trái chứa thẻ ul như trên và ô bên phải sẽ chứa giá trị trả về của lần lượt từng câu lệnh phía trên.

  • lorem isum1
  • lorem isum2
  • lorem isum3
  • lorem isum4


Code


<style>
.fly {
float:left;
display:inline;
}
.clean{
clear:both;
}
.current{
color:red;
}
</style>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#butEmpty").click(function(){
var rmvObj = jQuery("#test_ul").empty();
jQuery("#showReturn").html(rmvObj);
});
jQuery("#butRemove").click(function(){
var rmvObj = jQuery("#test_ul").remove();
jQuery("#showReturn").html(rmvObj);
});
});
</script>
<div>
<div class="fly" style="width:200px;border:1px solid gray;height:120px;">
<ul id="test_ul">
<li>lorem isum1</li>
<li>lorem isum2</li>
<li>lorem isum3</li>
<li>lorem isum4</li>
</ul>
</div>
<div class="fly" style="margin:0px 5px;">
<input type="button" value="empty" id="butEmpty"/><br/>
<input type="button" value="remove" id="butRemove"/><br/>
</div>
<div class="fly" style="width:200px;border:1px solid gray;height:120px;" id="showReturn"></div>
<div class="clean"></div>
</div>

jQuery - XML

Khởi tạo XML

Để khởi tạo XML trong jQuery ta làm như sau:

var xml = $('<xml>');
xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");

Biến xml giờ đây được hiểu là một XML object. Ta chỉ việc append các node con vào trong object này.

Thêm node

Hàm find được dùng để tìm kiếm các thẻ trong xml. Ví dụ ta muốn tạo một danh sách employee. Ta làm như sau:

 //Đầu tiên ta tạo thẻ employees chứa các thẻ employee
xml.append("<employees></employees>");

//Tạo thẻ employee con
var employee = "";
employee += "<employee>";
employee += "<name>Tran Van A</name>";
employee += "<date>202020</date>";
employee += "<email>abc@yahoo.com</email>";
employee += "<phone>00000000</phone>";
employee += "</employee>";

// Sau đó ta tạo các thẻ employee con.
// Ta dùng hàm find để tìm thẻ employees vừa tạo
xml.find("employees").each(function(){

// Thêm thẻ employee vào thẻ employees
jQuery(this).append(employee);

});

Cập nhật thông tin node

Sau khi thực hiện các lệnh trên ta có được nội dung xml như sau:

<?xml version="1.0" encoding="UTF-8"?>
<employees>
<employee>
<name>Tran Van A</name>
<date>202020</date>
<email>abc@yahoo.com</email>
<phone>00000000</phone>
</employee>
</employees>

Ta cần cập nhật thông tin tên của employee thành Nguyễn Văn B. Ta làm như sau:

// Lấy ra danh sách tất cả các thẻ name trong file xml
//Cách một
xml.find("name").each(function(){
if (jQuery(this).text()=="Tran Van A"){
jQuery(this).text("Nguyen Van B");
}
});

//Cách hai
xml.find("employees").each(function(){
jQuery(this).find("employee").each(function(){
jQuery(this).find("name").each(function(){
if(jQuery(this).text()=="Tran Van A"){
jQuery(this).text("Nguyen Van B");
}
});
});
});

Xóa một node

Sau khi thực hiện lệnh cập nhật, ta có nội dung xml như sau

<?xml version="1.0" encoding="UTF-8"?>
<employees>
<employee>
<name>Nguyen Van B</name>
<date>202020</date>
<email>abc@yahoo.com</email>
<phone>00000000</phone>
</employee>
</employees>

Bây giờ ta sẽ xóa node name của employee có tên là Nguyen Van B ra khỏi nội dung XML(Dùng hàm remove)

xml.find("employees").each(function(){
jQuery(this).find("employee").each(function(){
jQuery(this).find("name").each(function(){
if(jQuery(this).text()=="Nguyen Van B"){
// Dùng hàm remove để xóa node
jQuery(this).remove();
}
});
});
});

Nội dung file XML cuối cùng sẽ như sau

<?xml version="1.0" encoding="UTF-8"?>
<employees>
<employee>
<date>202020</date>
<email>abc@yahoo.com</email>
<phone>00000000</phone>
</employee>
</employees>