<!-- 1.封装一个简单地ajax函数 -->
<!-- 2.实现瀑布流 -->
<script src = "./demo.js"></script>
<script>
ajax('./server/data.json','GET','',function(res){
console.log(res);
},true)
</script>
/**
*
* ajax : async javascript and json
* 主要用来实现前后端的数据交流
* A 要发送一个信息给 B
* 请求当中需要有的基本信息:
* 1. B的地址
* 2. 请求方式 GET POST
* 3. 请求数据
* 4. 状态码 (B是否正常接收数据)
* 5. 响应数据
* XMLHTTPRequest
*
* 五层网络模型:
* 应用层
* 传输层
* 网络层
* 数据链路层
* 物理层
*
*/
function ajax(url, type, data, success, flag) {
var xhr = null;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
xhr.onreadystatechange = function() {
// 0 1 2 3 4
// 0: 当前代理已经被创建 还没有调用open方法
// 1: 调用了open方法 建立连接
// 2: send方法已经被调用
// 3: 代表正在接收响应信息
// 4: 代表响应数据全部发送完成
// console.log(xhr.readyState)
// 404 400
if (xhr.readyState == 4) {
if (xhr.status == 200) {
success(JSON.parse(xhr.responseText))
} else {
console.log('error')
}
}
}
if (type == 'GET') {
xhr.open(type, url + '?' + data, flag);
xhr.send();
} else if (type == 'POST'){
xhr.open(type, url, flag);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// key=value&key1=value1
xhr.send(data);
}
}
-------------------------------------jquery中的ajax----------------------------------------------------
function dealDate(res){
console.log(res);
}
$.ajax({
url: " " ,
data:{
page: 1,
size: 10,
cb:'dealData'
},
beforeSend:function(xhr,data){
console.log(xhr,data);
},
// 希望拿取到的数据类型
dataType:'json',
success: function(res){
},
error:function(){
console.log('error',err)
}
})
</script>