原生js实现ajax及get post方法
栏目: JavaScript · 发布时间: 6年前
内容简介:使用过以下为个人类库随笔一行 这是前端最好的时代, 这也是前端最坏的时代。 众多前端框架满天飞,随着 jQuery 在前端行业的慢慢弱化,总是会有一种斯人远去,何者慰籍的感觉。互勉吧,各位。
使用过 jQuery
的同学,应该对事件绑定方法 ajax
有一定的了解。 在个人类库 jTool
中实现了这个方法,这里就来细说下原生实现方式。
实现方式
以下为个人类库 jTool 中 Ajax 实现方式。 代码中使用到一个基础方法对象 utilities ,该对象为 jTool 的基础类。 如果想了解更多,可以通过点击进入查看原码。
/*
* ajax
* type === GET: data格式 name=baukh&age=29
* type === POST: data格式 { name: 'baukh', age:29 }
* 与 jquery 不同的是,[success, error, complete]返回的第二个参数, 并不是返回错误信息, 而是错误码
* */
var extend = require('./extend');
var utilities = require('./utilities');
function ajax(options) {
var defaults = {
url: null,// 请求地址
type: 'GET',// 请求类型
data: null,// 传递数据
headers: {},// 请求头信息
async: true,// 是否异步执行
beforeSend: utilities.noop,// 请求发送前执行事件
complete: utilities.noop,// 请求发送后执行事件
success: utilities.noop,// 请求成功后执行事件
error: utilities.noop// 请求失败后执行事件
};
options = extend(defaults, options);
if (!options.url) {
utilities.error('jTool ajax: url不能为空');
return;
}
var xhr = new XMLHttpRequest();
var formData = '';
if (utilities.type(options.data) === 'object') {
utilities.each(options.data, function (key, value) {
if(formData !== '') {
formData += '&';
}
formData += key + '=' + value;
});
}else {
formData = options.data;
}
if(options.type === 'GET' && formData) {
options.url = options.url + (options.url.indexOf('?') === -1 ? '?' : '&') + formData;
formData = null;
}
xhr.open(options.type, options.url, options.async);
for (var key in options.headers) {
xhr.setRequestHeader(key, options.headers[key]);
}
// xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
// 执行发送前事件
options.beforeSend(xhr);
// 监听onload并执行完成事件
xhr.onload = function() {
// jquery complete(XHR, TS)
options.complete(xhr, xhr.status);
};
// 监听onreadystatechange并执行成功失败事件
xhr.onreadystatechange = function() {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
// jquery success(XHR, TS)
options.success(xhr.response, xhr.status);
} else {
// jquery error(XHR, TS, statusText)
options.error(xhr, xhr.status, xhr.statusText);
}
};
xhr.send(formData);
}
function post(url, data, callback) {
ajax({ url: url, type: 'POST', data: data, success: callback });
}
function get(url, data, callback) {
ajax({ url: url, type: 'GET', data: data, success: callback });
}
module.exports = {
ajax: ajax,
post: post,
get: get
};
复制代码
随笔一行 这是前端最好的时代, 这也是前端最坏的时代。 众多前端框架满天飞,随着 jQuery 在前端行业的慢慢弱化,总是会有一种斯人远去,何者慰籍的感觉。互勉吧,各位。
另推荐个表格组件 gridManager
以上所述就是小编给大家介绍的《原生js实现ajax及get post方法》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Programming PHP
Rasmus Lerdorf、Kevin Tatroe、Peter MacIntyre / O'Reilly Media / 2006-5-5 / USD 39.99
Programming PHP, 2nd Edition, is the authoritative guide to PHP 5 and is filled with the unique knowledge of the creator of PHP (Rasmus Lerdorf) and other PHP experts. When it comes to creating websit......一起来看看 《Programming PHP》 这本书的介绍吧!