We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
在jquery中,ajax的调用方式如下:
$.ajax({ url: 'xxx', type: 'GET', success: function () { } }) $.get('xxx', fucntion(){}) $.post('xxx', { a=1, b=2 }, fucntion(){})
今天,我们就来实现这样的调用方式。搭建的基本骨架如下:
var $ = (function () { return { ajax: function (opt) { }, get: function (url, success) { }, post: function (url, data, success) { } } })();
这样的话,可以直接通过$.ajax()、$.get()、$.post()调用。接下来完善其中的功能,先实现一个doAjax函数,用来发送ajax请求:
doAjax
function doAjax(opt) { // 拿到options中的属性,如type、async、url、data属性或者error、success、complete等回调函数 var opt = opt || {}, type = (opt.type || 'GET').toUpperCase(), async = opt.async || true, url = opt.url, data = opt.data || null, error = opt.error || function () { }, success = opt.success || function () { }, complete = opt.complete || function () { } // 如果没有传入url参数,则直接抛错 if (!url) { throw new Error('no url') } // 发送ajax请求 o.open(type, url, async) type === 'POST' && o.setRequestHeader('Content-type', 'application/x-www-form-urlencoded') o.send(type === 'GET' ? null : _formatDatas(data)) o.onreadystatechange = function () { if (o.readyState === 4 && (o.status === 200 || status === 304)) { success(JSON.parse(o.responseText)) } else { error() } complete() } } // 工具函数,将key-value的object对象转化为类似a=1&b=2的字符串 function _formatDatas(obj) { var str = '' for (var key in obj) { str += key + '=' + obj[key] + '&' } return str.replace(/&$/, '') }
在ajax、get、post方法中可以直接进行使用了:
var $ = (function () { // 拿到浏览器自带的ajax方法,如果有XMLHttpRequest则直接使用,没有的话就用new ActiveXObject var o = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP') if (!o) { throw new Error('Your browser cannot support http') } function doAjax(opt) { // ... } return { ajax: function (opt) { doAjax(opt) }, get: function (url, success) { doAjax({ type: 'GET', url, success }) }, post: function (url, data, success) { doAjax({ type: 'POST', url, data, success }) } } })();
到这里,已经完成了以jquery形式发送ajax请求的功能~
The text was updated successfully, but these errors were encountered:
No branches or pull requests
在jquery中,ajax的调用方式如下:
今天,我们就来实现这样的调用方式。搭建的基本骨架如下:
这样的话,可以直接通过$.ajax()、$.get()、$.post()调用。接下来完善其中的功能,先实现一个
doAjax
函数,用来发送ajax请求:在ajax、get、post方法中可以直接进行使用了:
到这里,已经完成了以jquery形式发送ajax请求的功能~
The text was updated successfully, but these errors were encountered: