//封裝ajax function ajax(obj) { //建立xhr對象; var xhr = new XMLHttpRequest(); obj.method = obj.method.toUpperCase(); //異步調用 if (obj.async) { //監聽響應狀態 xhr.onreadystatechange = function() { if (xhr.readyState == 4) { callback(); } }; } //啓動HTTP請求 xhr.open(obj.method, obj.url, obj.async); xhr.responseType = "json"; if (obj.method === 'POST') { if (obj.isForm) { xhr.send(obj.data); } else { xhr.setRequestHeader('Content-Type', 'application/json'); xhr.send(JSON.stringify(obj.data)); } } else if (obj.method === 'GET') { xhr.send(); } //同步調用 if (!obj.async) { callback(); } function callback() { if (xhr.status == 200) { obj.success && obj.success(xhr.response); } else { obj.error && obj.error(xhr.response); } } }