您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

JavaScript自己封装ajax的js

2024/6/19 4:25:20发布37次查看
[javascript] /** * 执行基本ajax请求,返回xmlhttprequest * ajax.request({ * url * async 是否异步 true(默认) * method 请求方式 post or get(默认) * data 请求参数 (键值对字符串) * success 请求成功后响应函数,参数为xhr * error 请求失败后响应函数,参数为xhr * }); */ www.2cto.com ajax = function() { function request(opt) { function fn() { } var url = opt.url || ""; var async = opt.async !== false, method = opt.method || 'get', data = opt.data || null, success = opt.success || fn, error = opt.failure || fn; method = method.touppercase(); if (method == 'get' && data) { var args = ""; if(typeof data == 'string'){ //alert("string") args = data; }else if(typeof data == 'object'){ //alert("object") var arr = new array(); for(var k in data){ var v = data[k]; arr.push(k + "=" + v); } args = arr.join("&"); } url += (url.indexof('?') == -1 ? '?' : '&') + args; data = null; } var xhr = window.xmlhttprequest ? new xmlhttprequest() : new activexobject('microsoft.xmlhttp'); xhr.onreadystatechange = function() { _onstatechange(xhr, success, error); }; xhr.open(method, url, async); if (method == 'post') { xhr.setrequestheader('content-type', 'application/x-www-form-urlencoded;'); } xhr.send(data); return xhr; } function _onstatechange(xhr, success, failure) { if (xhr.readystate == 4) { var s = xhr.status; if (s >= 200 && s < 300) { success(xhr); } else { failure(xhr); } } else { } } return { request : request }; }(); [javascript] ajax.request({ url : path + "/report/topn/topn_data.jsp", data : { datatype : datatype }, success : function(xhr) { ondata(xhr.responsetext); }, error : function(xhr) { } });
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product