1、主體:封裝ajax函數:ajaxFuncajax
function ajaxFunc(method, url, data, callback, flag) { //(1)建立ajax對象 var xhr; if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else { xhr = new ActiveXObject('Microsoft.XMLHttp'); } //(2)請求方式get||post method = method.toUpperCase(); if(method == 'GET'){ xhr.open(method, url, flag); xhr.send(); }else if(method == 'POST'){ xhr.open(method, url, flag); xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xhr.send(data); } //(3)監聽請求數據 xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ if(xhr.status == 200){ callback(xhr.responseText); } xhr = null; } } } //(4)回調函數對數據處理 function callback(requestData){ var obj = JSON.parse(requestData); }