<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p></p>
<button>展示ajax里的内容</button>
<script>
var oP=document.querySelector("p");
var oBtn=document.querySelector("button");
oBtn.onclick=function(){
ajax("data2.txt",{
// 拿到数据要干什么
"suncFn" : function(data){ //data是形参
oP.innerHTML=data;
},
"json" : true,
});
}
function ajax(url,option){
// 判断是否要清除缓存
// if(option.cache==undefined){
// var cache=true;
// }else{
// var cache=option.cache;
// }
var cache=option.cache==undefined ? true : option.cache; //默认cache是true(因为option里没有写cache时,在ajax里默认cache的值为true),说明有缓存,所以下面要用时间戳来清除缓存。(因为时间戳会获取每一刻时间的数据,所以即使后台数据改变了,利用时间戳也能显示页面上。但如果不用时间戳,因为之前显示的已经在浏览器上缓存了所以下次不刷新页面就显示不了新的内容)。这就是局部刷新——不用刷新页面就可以获得新的(后台数据改变)内容
var json=option.json==undefined ? false : option.json;
//默认json是false(接收的数据不用转换),如果想要获取的数据是json格式,就让option中的json为真,将获取的数据转换成josn格式即可(因为ajax从服务器上获取的对象xhr.responseText是字符串,一般都要转换)
var method=option.method || "get"; //默认的上传方法是get
var sucFn=option.suncFn || function(){};
var faiFn=option.failFn || function(){};
var data=option.data || ""; //因为用post上传,需要再send里传data,所以得判断有没有data,这个data和形参data不一样(这个data是上传数据时使用,形参里的data是从服务器获取的数据)
var xhr=new XMLHttpRequest();
if(method=="get"){ //get上传数据的方式
// xhr.open(method,url+"?"+data,true);
// 处理缓存
xhr.open(method,(cache ? url+"?"+data+Date.now() : url+"?"+data),true);
xhr.send();
}else{ //post上传数据的方式
// xhr.open(method,url,true);
// 处理缓存
xhr.open(method,(cache ? url+"?"+Date.now() : url),true);
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
xhr.send(data);//data是上传的数据
}
// xhr.open("get",url,true);
// xhr.send();
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status==200){
// sucFn(xhr.responseText); //xhr.responseText是实参,传给data
sucFn(json ? JSON.parse(xhr.responseText) : xhr.responseText);
}else{
faiFn();
}
}
}
}
</script>
</body>
</html>
08-01
07-19
07-19
07-19
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交