Fork me on GitHub

AJAX的封装

ajax的封装:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
function ajax(method,url,data,success){
var xhr;
try{
//尝试执行try中的代码,如有错误,执行catch中的代码并返回错误信息
xhr=new XMLHttpRequest();
//throw new Error('手动报错');
}catch(e){
xhr=new ActiveXObject('Microsoft.XMLHTTP');
//alert(e);
}
var btn=document.getElementById("btn");
btn.onclick=function (){
setInterval(function (){
var xhr=new XMLHttpRequest();
if(method == "get" && data){
url+="?"+data;
}
xhr.open(method,url,true);
if(method == "get"){
xhr.send();
}else{
xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
xhr.send(data);
}
xhr.onreadystatechange=function (){
if(xhr.readyState == 4){
if(xhr.status == 200){
success && success(xhr.responseText)
}else{
alert("出错了"+xhr.status);
}
}
};
},1000)
}
}

数据:

1
2
3
4
5
6
7
8
9
10
11
12
<?php
header('content-type:text.html;charset:"utf-8"');
error_reporting(0);
$news=array(
array("title"=>"中国又一工程惊艳世界:世界最深高铁站","date"=>"[2017-7-5]"),
array("title"=>"院士:让中国转基因鲤鱼尽快游向餐桌 ","date"=>"[2017-7-5]"),
array("title"=>"中戏老师怒怼战狼2:一文不值心理变态","date"=>"[2017-7-5]"),
array("title"=>"陕西一区委书记赴宴被富豪打 纪委披露","date"=>"[2017-7-5]"),
array("title"=>"2.3公里路司机绕成30公里 滴滴愿赔1千","date"=>"[2017-7-5]")
);
echo json_encode($news);
?>
据说帅的人都赏给博主几块钱零花钱。