ajax前后端交互原理(7)
7.ajax函数封装
7.1.实例引入
需求: 每秒钟请求一次服务器 获取到数据
实现: 把ajax进行封装
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="ajax.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
window.onload = function(){
var oBtn = document.getElementById("btn");
oBtn.onclick = function(){
setInterval(function(){
ajax("get",'getData.php','',function(data){
var oUl = document.getElementById('ul1');
var html = ''
for(var i = 0; i < data.length; i++) {
var oli = document.createElement('li');
html += '<li>'+ data[i].title + '[' + data[i].time + ']</li>';
}
oUl.innerHTML = html;
});
},1000)
}
}
</script>
</head>
<body>
<input type="button" id="btn" value="获取数据" />
<ul id="ul1">
</ul>
</body>
</html>
7.2.ajax代码,普通封装:
function ajax(method,url,data,sucess) {
//创建ajax对象
var xhr = null;
try {
xhr = new XMLHttpRequest();
} catch(e) {
xhr = new ActiveXobject('Microsoft.XMLHTTP');
}
if(!method || method == "get"){
method = "get";
//打开要获取文件的地址
if(data){
url = url+"?"+data;
}
xhr.open(method, url, true);
//发送请求
xhr.send();
}else{
method = "post";
xhr.open(method, url, true);
if(data){
//发送请求
xhr.send();
}else{
xhr.send(data);
}
}
//alert(xhr.responseText);
//监听请求状态
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
var data = JSON.parse(xhr.responseText);
sucess && sucess();
}
}
}
7.3.ajax代码,封装成对象的传参的形式:
function ajax(obj) {
//创建ajax对象
var xhr = null;
try {
xhr = new XMLHttpRequest();
} catch(e) {
xhr = new ActiveXobject('Microsoft.XMLHTTP');
}
if(!obj.method || obj.method == "get"){
obj.method = "get";
//打开要获取文件的地址
if(obj.data){
obj.url = obj.url+"?"+obj.data;
}
xhr.open(obj.method, obj.url, true);
//发送请求
xhr.send();
}else{
obj.method = "post";
xhr.open(obj.method, obj.url, true);
if(data){
//发送请求
xhr.send();
}else{
xhr.send(obj.data);
}
}
//alert(xhr.responseText);
//监听请求状态
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
var data = JSON.parse(xhr.responseText);
obj.success && obj.success(data);
}
}
}
螺钉课堂视频课程地址:http://edu.nodeing.com