这种封装 ajax 的方法如何(以 get 请求为例)?
下面是我对 ajax 中的 get 请求的封装:
var ajax = {
// var callback = function (responseText) {
// TODO with responseText
// }
get: function (url, callback) {
var xhr = new XMLHttpRequest();
xhr.url = url;
xhr.open('GET', url);
xhr.send(null);
xhr.onreadystatechange = (function (xhr) {
var sub = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
callback(xhr.responseText);
} else if (xhr.status === 404) {
console.log('GET (' + xhr.url + '): 404 not found!');
}
};
return sub;
}(xhr));
},
};
一直觉得 ajax 没有什么特殊的内容,只是一个工具而已。现在的公司在招聘是提的要求都是要求什么熟悉“记忆性的知识”,我觉得这种知识最容易获取了。所以我觉得在招聘时,根本不必要求熟悉 ajax,因为它就是那样,你需要的时候去获取就行了,它就那点东西。
3 回复
很多前端框架都有这个封装把 比如 angular 的 $http
var ajax = {};
var parse = function (req) {
var result;
try {
result = JSON.parse(req.responseText);
} catch (e) {
result = req.responseText;
}
return [result, req];
};
var xhr = function (type, url, data) {
var methods = {
success: function () {},
error: function () {}
};
var XHR = window.XMLHttpRequest || ActiveXObject;
var request = new XHR('MSXML2.XMLHTTP.3.0');
request.open(type, url, true);
request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
request.onreadystatechange = function () {
if (request.readyState === 4) {
if (request.status === 200) {
methods.success.apply(methods, parse(request));
} else {
methods.error.apply(methods, parse(request));
}
}
};
request.send(data);
return {
success: function (callback) {
methods.success = callback;
return methods;
},
error: function (callback) {
methods.error = callback;
return methods;
}
};
};
ajax['get'] = function (src) {
return xhr('GET', src);
};
ajax['put'] = function (url, data) {
return xhr('PUT', url, data);
};
ajax['post'] = function (url, data) {
return xhr('POST', url, data);
};
ajax['delete'] = function (url) {
return xhr('DELETE', url);
};
https://github.com/toddmotto/atomic/blob/master/dist/atomic.js
@ifeiteng 抱歉,看不出这种方式有什么特别好的地方,或许 ajax 很平凡