AJAX&XMLHttpRequest

HTTP Requestjavascript

GET for acquire data, pass data in URLhtml

POST upload datajava

AJAX (Asynchronous JavaScript and XML) is a technology used to quickly create dynamic web page. It exchange small data with servers in backends, and refresh web page asynchronously, which results in refreshing part of a web page, instead of reload the whole page.web

XMLHttpRequest is the basis of AJAX (IE7+ Firefox Chrome Safari and Opera all in-build XMLHttpRequest object, while old IEs use ActiveX). Its function is exchanging data with servers using open(method,url,async) and send(string), method contains GET&POST. When used for AJAX, the async parameter must be true.ajax

AJAX & XMLHttpRequest服務器

Many tasks in server is time-cost, the application may hang or stop before the occurrence of AJAX. With AJAX, JavaScript need not wait for response, instead, they can execute other script while waiting and process after receiving the response.. Changes of value of readyState (0-4) will trigger onreadystatechange event, then execute other process in the function, the response is ready when readyState is 4 and status is 200. You can acquire the response using responsText (string type) and reponseXML (XML format).app

AJAX Request Process異步

1. create ajax objectasync

if (window.XMLHttpRequest)ui

  xmlhttp=new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari

else

  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
2. connect to server

xmlhttp.open(‘GET’,url,true)

3. send request

xmlhttp.send()

4. receive response

xmlhttp.onreadystatechange=function()

{

  if (xmlhttp.readyState==4 && xmlhttp.status==200)

    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

}

Sample

function ajax(url, fnSucc, fnFaild){

  //1.建立對象

  var oAjax = null;

  if(window.XMLHttpRequest){

    oAjax = new XMLHttpRequest();

  }else{

    oAjax = new ActiveXObject("Microsoft.XMLHTTP");

  }

  //2.鏈接服務器

  oAjax.open('GET', url, true); //open(方法, url, 是否異步)

  //3.發送請求  

  oAjax.send();

  //4.接收返回

  oAjax.onreadystatechange = function(){ //OnReadyStateChange事件

    if(oAjax.readyState == 4){ //4爲完成

      if(oAjax.status == 200){ //200爲成功

        fnSucc(oAjax.responseText)

      }else{

        if(fnFaild){

          fnFaild();

        }

      }

    }

  };

}


<!DOCTYPE HTML>

<html lang="en-US">

<head>

<meta charset="UTF-8">

<title>ajax基礎</title>

</head>

<body>

點擊按鈕的時候,讀取abc.txt<input id="btn" type="button" value="讀取"/><br/>

<div id="con"></div>

</body>

</html>

<script type="text/javascript" src="ajax.js"></script>

<script type="text/javascript">

window.onload = function(){

var oBtn = document.getElementById('btn');

var oCon = document.getElementById('con');

oBtn.onclick = function(){

ajax('abc.txt',function(str){

oCon.innerHTML = str;

});

}

}

</script>

相關文章
相關標籤/搜索