<script>
//簡單的封裝一個ajax
/**
* ajax: async javascript and json
* 主要用來實作前后端的資料交流
* A要發送一個資訊給B
* 請求當中需要有的基本資訊
* 1.B的地址
* 2.請求方式
* 3.請求資料
* 4.狀態碼(B是否正常接收資料)
* 5.回應資料
* XMLHttpRequest物件
* 五層網路模型:
* 物理層
* 資料鏈路層
* 網路層
* 傳輸層
* 應用層
*/
function ajax(options){
var xhr = null;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{//兼容IE6
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
xhr.onreadystatechange = function(){//監聽回應事件
//readyState的幾個值
//0:當前代理已經被創建,還沒有呼叫open方法
//1:呼叫了open方法,建議連接
//2:send方法已經被呼叫
//3:代表正在接收相應資訊
//4:代表回應資料全部發送完成
//status的幾個值
//200:正常回應
if(xhr.readyState == 4 && ){
if(xhr.status == 200){
options.success(JSON.parse(xhr.responseText));
}else{
console.log('error');
}
}
}
if(options.type == 'GET'){
xhr.open(options.type, options.url + '?' + options.data, options.flag);
xhr.send();
}else if(options.type == 'POST'){
xhr.open(options.type, options.url, options.flag);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');//請求頭的編碼型別:key=value&key1=value1
xhr.send(options.data);
}
}
</script>
Ajax.js
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/88379.html
標籤:JavaScript
