AJAX簡介

AJAX 是一種在無需重新載入整個網頁的情況下,能夠更新部分網頁的技術。

一.ajax是什麼:
(1).ajax是非同步 JavaScript 和 XML,英文全程是Asynchronous JavaScript and XML。
(2).ajax可以透過與後台進行少量的資料交換,實現對局部網頁進行非同步更新,避免了要刷新這個頁面的情況。
在通常情況下,如果要更新網頁的數據,需要刷新整個頁面,如果利用ajax,那麼就可以只進行局部刷新即可。

AJAX 工作原理

ajax.gif

二.AJAX是基於現有的Internet標準:
ajax並不是新的技術,而是基於現有的Internet標準與技術:
(1).XMLHttpRequest 物件(非同步的與伺服器交換資料)。
(2).JavaScript/DOM (訊息顯示/互動)。
(3).CSS (給資料定義樣式)。
(4).XML (作為轉換資料的格式)。
三.程式碼實例:
上面對ajax做了一個基本介紹,下面就是一個簡單的程式碼實例,先感受一下它的作用:

<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="//m.sbmmt.com/" />
<title>php中文网</title>
<script>
function loadXMLDoc(){
  var xmlhttp;
  if (window.XMLHttpRequest){
    xmlhttp=new XMLHttpRequest();
  }
  else{
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function(){
    if(xmlhttp.readyState==4 && xmlhttp.status==200){
      document.getElementById("show").innerHTML=xmlhttp.responseText;
    }
  }
  xmlhttp.open("GET","demo/ajax/txt/demo.txt",true);
  xmlhttp.send();
}
window.onload=function(){
  var obt=document.getElementById("bt");
  obt.onclick=function(){
    loadXMLDoc();
  }
}
</script>
</head>
<body>
<div id="show"><h2>原来的内容</h2></div>
<button type="button" id="bt">查看效果</button>
</body>
</html>

程式碼中的demo/ajax/txt/demo.txt可變更路徑在本機創建,觀察效果。

#
繼續學習
||
<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <meta name="author" content="//m.sbmmt.com/" /> <title>php中文网</title> <script> function loadXMLDoc(){ var xmlhttp; if (window.XMLHttpRequest){ xmlhttp=new XMLHttpRequest(); } else{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function(){ if(xmlhttp.readyState==4 && xmlhttp.status==200){ document.getElementById("show").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","demo/ajax/txt/demo.txt",true); xmlhttp.send(); } window.onload=function(){ var obt=document.getElementById("bt"); obt.onclick=function(){ loadXMLDoc(); } } </script> </head> <body> <div id="show"><h2>原来的内容</h2></div> <button type="button" id="bt">查看效果</button> </body> </html>
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!