原生JS實現AJAX、JSONP及DOM載入完成事件,並提供對應方法
阿新 • • 發佈:2019-02-13
JS原生AJAX
ajax:一種請求資料的方式,不需要重新整理整個頁面; ajax的技術核心是 XMLHttpRequest 物件; ajax 請求過程:建立 XMLHttpRequest 物件、連線伺服器、傳送請求、接收響應資料;
下面簡單封裝一個函式,之後稍作解釋
ajax({
url:
"./testXhr.php" ,
//請求地址
type:
"POST" ,
//請求方式
data:
{ name: "WeideMo" ,
age: 26 }, //請求引數
dataType:
"json" ,
success:
function
(response, xml) {
//
此處放成功後執行的程式碼
},
fail:
function
(status) {
//
此處放失敗後執行的程式碼
}
});
function
ajax(options) {
options
= options || {};
options.type
= (options.type || "GET" ).toUpperCase();
options.dataType
= options.dataType || "json" ;
var
params = formatParams(options.data);
//建立
- 非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;
//此處不判斷304,因為增加隨機數後,不命中快取
if
(status >= 200 && status < 300) {
options.success
&& options.success(xhr.responseText, xhr.responseXML);
}
else
{
options.fail
&& options.fail(status);
}
}
|