1、打开服务器WampServer;
2、将文件放置在WampServer的www文件夹下;
3、打开时网页地址栏为localhost+www下的地址。eg:http://localhost/myworld/5.19ajax/index.html?__hbt=1495158145298
4、调用方式:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<input type="button" id="btn" value="提交"/>
<span id="info"></span>
</body>
<script src="js/ajax_util.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
var btn=document.getElementById('btn');
var info=document.getElementById('info');
btn.onclick=function(){
//date为空,无数据传送;
ajax('GET','/myworld/5.19ajax/span.txt','',function(str){
info.innerHTML=str;
})
}
</script>
</html>
函数为:
/*
* ajax 4条线
* 第3条线由后台完成,直接调用
*/
function ajax(method,url,data,fn){
//1
var xhr;
if (window.XMLHttpRequest) {
xhr=new XMLHttpRequest();
}else{
xhr=new ActiveXObject('Microsoft XMLHTTP');
};
//2
if (method=='GET'&&data) {
url=url+'?'+data;
};
xhr.open(method,url,true);
if(method=='GET'){
xhr.send(null);
}else{
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send(data);
};
//4
xhr.onreadystatechange=function(){
if (xhr.readyState==4) {
if (xhr.status==200) {
if (xhr.responseXML) {
fn(xhr.responseXML);
}else{
fn(xhr.responseText);
};
}else{
console.log('出错状态为:'+xhr.status);
};
}
};
};