2016年8月9日 星期二

jQuery Ajax Practice

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

1.Html file

  1. <!doctype html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <link rel="stylesheet" href="">
  6. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  7. <title>ajax</title>
  8. <script>
  9. $(document).ready(function(){
  10. $("#button1").click(function(){
  11. $("#result").load("testHtml.html");
  12. });
  13. $("#button2").click(function(){
  14. $("#result").load("test.txt", function(responseTxt, statusTxt, xhr){
  15. if(statusTxt == "success")
  16. alert("External content loaded successfully!");
  17. if(statusTxt == "error")
  18. alert("Error: " + xhr.status + ": " + xhr.statusText);
  19. });
  20. });
  21. $("#button3").click(function(){
  22. $.get('testHtml.html', {name:"ian",age:"18"},function(data,status){alert(status)});
  23. alert("haha");
  24. });
  25. $("#button4").click(function(){
  26. $.post('testHtml.html', {name:"ian",age:"18"},function(data,status){alert(status)});
  27. alert("haha2");
  28. });
  29. $("#button5").click(function(){
  30. $.ajax({url:"testHtml.html", success:function(result){
  31. $("#result").html(result);
  32. }});
  33. });
  34. });
  35. </script>
  36. </head>
  37. <body>
  38. <button id="button1">ajax</button>
  39. <button id="button2">ajax2</button>
  40. <button id="button3">ajax3</button>
  41. <button id="button4">ajax4</button>
  42. <button id="button5">ajax5</button>
  43. //原畫面的div
  44. <div style="border:2px red solid;width:200px">
  45. </div>
  46. <div id="result">
  47. </div>
  48. </body>
  49. </html>

2.test.txt

  1. <h2>jQuery and AJAX is FUN!!!</h2>
  2.  
  3. <p id="p1">This is some text in a paragraph.</p>

3.testHtml.html

  1. <!doctype html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <link rel="stylesheet" href="">
  6. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  7. <title>aaa</title>
  8. </head>
  9. <body>
  10. <h2>Hello my name is ajax</h2>
  11. <div style="border:2px blue solid;width:200px">
  12. aa
  13. </div>
  14. </body>
  15. </html>

沒有留言:

張貼留言