Skip to content

Instantly share code, notes, and snippets.

@zhlinh
Created August 7, 2015 11:05
Show Gist options
  • Save zhlinh/e9f3b512f741a9e007d3 to your computer and use it in GitHub Desktop.
Save zhlinh/e9f3b512f741a9e007d3 to your computer and use it in GitHub Desktop.
Ajax - Asynchronous request
// file: scripts/addLoadEvent.js
function addLoadEvent(func){
var oldonload = window.onload;
if(typeof window.onload != "function"){
window.onload = func;
}else {
window.onload = function(){
oldonload();
func();
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Ajax</title>
</head>
<body>
<div id="new" ><p>why?</p> </div>
<script src="scripts/addLoadEvent.js"></script>
<script src="scripts/getHttpObject.js"></script>
<script src="scripts/getNewContent.js"></script>
</body>
</html>
// file: scripts/getHttpObject.js
function getHttpObject() {
if (typeof XMLHttpRequest == "undefined"){
XMLHttpRequest = function(){
try{
return new ActiveXObject("Msxml2.XMLHTTP6.0");
}catch(e){
}
try{
return new ActiveXObject("Msxml2.XMLHTTP3.0");
}catch(e){
}
try{
return new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
}
return false;
}
}else{
return new XMLHttpRequest();
}
}
// file: scripts/getNewContent.js
// window.onload = getNewContent;
addLoadEvent(getNewContent);
function getNewContent(){
var request = getHttpObject();
// var request = new XMLHttpRequest();
if(request){
request.open("GET","example.txt",true);
request.onreadystatechange = function(){
if(request.readyState == 4){
// 测试异步
alert("Response Received");
var para = document.createElement("p");
var txt = document.createTextNode(request.responseText);
para.appendChild(txt);
document.getElementById("new").appendChild(para);
}
}
request.send(null);
} else {
alert("Sorry, your browser doesn\'t support XMLHttpRequest");
}
// 测试异步
alert("Function Done.");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment