Javascript 封装的ajax方法
转:夕阳茶
Javascript 封装的ajax方法
- //ajax的封装
- var Ajax = {
- method: 'post',
- asynchronous: true,
- proxy: null,
- contentType: "application/x-www-form-urlencoded",
- create: function () {
- var me = this, proxy;
- var xmlhttpObj = ['MSXML2.XMLHTTP.3.0',
- 'MSXML2.XMLHTTP',
- 'Microsoft.XMLHTTP'];
- if (window.XMLHttpRequest)// firefox
- {
- proxy = new XMLHttpRequest();
- }
- else if (typeof ActiveXObject != "undefined")// IE
- {
- for (var i = 0, len = xmlhttpObj.length; i < len; i++) {
- if (!proxy)
- proxy = new ActiveXObject(xmlhttpObj[i]);
- else
- break;
- }
- }
- return proxy;
- },
- stateChange: function (proxy, callback) {
- var me = this;
- var readyState = proxy.readyState;
- if (readyState == 4 && proxy.status == 200)
- (callback || function () { }).call(me, proxy.responseText, proxy);
- },
- analyzeParam: function (params) {
- var arrp = [];
- for (var p in (params || {})) {
- arrp.push("&" + p + "=" + params[p]);
- }
- return arrp.join().replace(/\,/g, "");
- },
- request: function (cfg) {
- var me = this;
- var proxy = me.create();
- if (proxy) {
- proxy.onreadystatechange = function () {
- me.stateChange.call(me, proxy, cfg.callback);
- };
- }
- var param = me.analyzeParam(cfg.params);
- try {
- proxy.open(me.method, cfg.url, me.asynchronous);
- proxy.setRequestHeader("Content-type", me.contentType);
- proxy.send(me.analyzeParam.call(me, cfg.params));
- }
- catch (ex) {
- alert(ex.message)
- }
- }
- };
- //调用方法
- Ajax.request({
- url:"text.aspx",
- params:{name:'aa',age:20},
- callback:function(response){alert(response)}
- });
复制代码
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论