2016年8月9日 星期二

jQuery Ajax Practice

Note:
- 實做Ajax中的 load()、.get()、.post()、ajax()方法
- 運作方式:
- 根據不同按鈕,觸發不同的ajax事件,回傳不同的資料,並將回傳的資料塞入指定的div中

1.Html file

<!doctype html>
<html>
 <head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <title>ajax</title>
  <script>
   $(document).ready(function(){
    $("#button1").click(function(){
     $("#result").load("testHtml.html");
    });        
    $("#button2").click(function(){
     $("#result").load("test.txt", function(responseTxt, statusTxt, xhr){
     if(statusTxt == "success")
      alert("External content loaded successfully!");
     if(statusTxt == "error")
      alert("Error: " + xhr.status + ": " + xhr.statusText);
      });
     });          
    $("#button3").click(function(){
     $.get('testHtml.html', {name:"ian",age:"18"},function(data,status){alert(status)});
     alert("haha");
    });    
    
    $("#button4").click(function(){
     $.post('testHtml.html', {name:"ian",age:"18"},function(data,status){alert(status)});
     alert("haha2");
    });    
    $("#button5").click(function(){
     $.ajax({url:"testHtml.html", success:function(result){
      $("#result").html(result);
     }});
    });
   });
  </script>
 </head>
 <body>
  <button id="button1">ajax</button>
  <button id="button2">ajax2</button>
  <button id="button3">ajax3</button>
  <button id="button4">ajax4</button>
  <button id="button5">ajax5</button>
//原畫面的div
  <div style="border:2px red solid;width:200px">
  </div>
  <div id="result">
  </div>
 </body>
</html>

2.test.txt

<h2>jQuery and AJAX is FUN!!!</h2>

<p id="p1">This is some text in a paragraph.</p>

3.testHtml.html

<!doctype html>
<html>
 <head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="">  
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <title>aaa</title>  
 </head>
 <body>
  <h2>Hello my name is ajax</h2>
  <div style="border:2px blue solid;width:200px">
  aa
  </div>  
 </body>
</html>

沒有留言:

張貼留言