HTTP Request

GET for acquire data, pass data in URL

POST upload data

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.

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 & 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).

AJAX Request Process

1. create ajax object

if (window.XMLHttpRequest)

  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>

posted on 2017-08-22 11:04  Helenbj  阅读(127)  评论(0编辑  收藏  举报