Site icon Thiết kế Website tại Vinh Nghệ An Hà Tĩnh

Ví dụ đơn giản về Ajax và jQuery

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

<html>
<head>
 <script src="https://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>

 

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

<html>
<head>
 <script src="https://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
?>

 

DEMO | DOWNLOAD

5/5 - (2 bình chọn)
Exit mobile version