<!DOCTYPE html>
<html>
<head>
<title>ajax架構</title>
<meta charset="utf-8">
<script type="text/javascript">
function ajax(url,success,error){
if(window.XMLHttpRequest){
var oAjax = new XMLHttpRequest();
}
else{
var oAjax = new ActiveXObject('Microsoft.XMLHTTP');
}// 建立ajax ,並且需要做相容 IE6是不支援XMLHttpRequest對象
oAjax.open('post',url,true);//串連open(方法,檔案名稱,非同步傳輸(true)) 同步傳輸(false)
oAjax.send();//發送請求
//接收結果
oAjax.onreadystatechange = function(){
if(oAjax.readyState==4){
//是否完成狀態
if(oAjax.status>=200&&oAjax.status<300||oAjax.status==304){
//解析完成 2XX或緩衝304
if(success){
success(oAjax.responseText);
//responseText解析文字
}
}
else{
if(error){
error();
}
}
}
}
}
window.onload = function(){
var obtn = document.getElementById('button1');
obtn.onclick = function(){
ajax('data.html',function(str){
alert(str);
},function(){
alert('讀取失敗');
})
}
}
</script>
</head>
<body>
<input type="button" id="button1" value="發送">
</body>
</html>
data.html
{‘userName’:'jeck'}