Js原生ajax的使用
1.首先創(chuàng)建一個(gè)XMLHttpRequest()對(duì)象
var xhr = XMLHttpRequest()
2.然后配置open()方法
open()有三個(gè)屬性配置
比如
xhr.open("get","http://local host/add.php",true)
第一個(gè)參數(shù)代表"get"或者"post",請(qǐng)求
第二個(gè)地址為要請(qǐng)求的地址
第三個(gè)參數(shù)true代表是異步請(qǐng)求
3.發(fā)送
xhr.send()
//發(fā)送請(qǐng)求
如果是get請(qǐng)求send()不加參數(shù),參數(shù)拼接到url 后面
如果是post請(qǐng)求,將傳遞的參數(shù)當(dāng)?shù)絪end()方法內(nèi)發(fā)送
比如,發(fā)送一個(gè)id=10的數(shù)據(jù)
xhr.send("id=10")
4.監(jiān)聽狀態(tài)
通過(guò)xhr.onreadystatechange來(lái)監(jiān)聽服務(wù)器狀態(tài)
當(dāng)xhr.readyState = 4 && xhr.status = 200的時(shí)候,說(shuō)明服務(wù)器響應(yīng)成功
xhr.onreadystatechange = function(){
if( xhr.readyState = 4 && xhr.status = 200){
//這時(shí)候說(shuō)明數(shù)據(jù)請(qǐng)求成功,成功的數(shù)據(jù)會(huì)存放在xhr.responseText屬性中
var data = xhr.responseText.
console.log(data)//這里就是從后臺(tái)請(qǐng)求的數(shù)據(jù),然后通過(guò)js將對(duì)應(yīng)的數(shù)據(jù)渲染到頁(yè)面上
/*在這里通常都是拼接字符串的操作,
所以當(dāng)我們拼接字符串的時(shí)候可以將整個(gè)字符串放到一個(gè)數(shù)組里
然后通過(guò)數(shù)組的join()方法將數(shù)組拼接成字符串可以簡(jiǎn)化字符串拼接的錯(cuò)誤)*/
}
}
如果需要跨域,就需要設(shè)置頭部信息
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
原生js封裝的ajax請(qǐng)求,需要的自行帶走(解決ie兼容性問(wèn)題)
function ajax(options) {
options = options || {};
options.type = (options.type || "GET").toUpperCase();
options.dataType = options.dataType || "json";
options.async = options.async==false?false:true;
var params = formatParams(options.data);
//創(chuàng)建 - 非IE6 - 第一步
if (window.XMLHttpRequest) {
var xhr = new XMLHttpRequest();
} else { //IE6及其以下版本瀏覽器
var xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
//接收 - 第三步
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
var status = xhr.status;
if (status >= 200 && status < 300) {
options.success && options.success(xhr.responseText, xhr.responseXML);
} else {
options.fail && options.fail(status);
}
}
}
//連接 和 發(fā)送 - 第二步
if (options.type == "GET") {
xhr.open("GET", options.url + "?" + params, options.async);
xhr.send(null);
} else if (options.type == "POST") {
xhr.open("POST", options.url, options.async);
//設(shè)置表單提交時(shí)的內(nèi)容類型
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(params);
}
}
//格式化參數(shù)
function formatParams(data) {
var arr = [];
for (var name in data) {
arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]));
}
arr.push(("v=" + Math.random()).replace(".",""));
return arr.join("&");
}