//封装ajax function ajax(obj) { //创建xhr对象; var xhr = new XMLHttpRequest(); //后面随机数防止浏览器缓存 obj.url = obj.url + "?rand=" + Math.random(); 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); if (obj.method == 'POST') { xhr.send(obj.data); } else { xhr.send(); } //同步调用 if (!obj.async) { callback(); } function callback() { try { var res = JSON.parse(xhr.response) } catch (e) { console.error(e) } if (xhr.status == 200) { obj.success && obj.success(res); } else { obj.error && obj.error(res); } } } ajax({ method: 'post', url: 'test.test.test', data: formData, async: true, success: function(res) { }, error: function(e) { }, });