博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
原生Js封装ajax方法
阅读量:4652 次
发布时间:2019-06-09

本文共 2063 字,大约阅读时间需要 6 分钟。

// ajax封装 function ajax(options) {
/** * 传入方式默认为对象 * */ options = options || {}; /** * 默认为GET请求 * */ options.type = (options.type || "GET").toUpperCase(); /** * 返回值类型默认为json * */ options.dataType = options.dataType || 'json'; /** * 默认为异步请求 * */ options.async = options.async || true; /** * 对需要传入的参数的处理 * */ var params = getParams(options.data);
   var p = options.url.indexOf("?") >= 0 ? "&" + params : "?" + params;
var xhr;     /**      * 创建一个 ajax请求      * W3C标准和IE标准      */     if (window.XMLHttpRequest){
/** * W3C标准 * */ xhr = new XMLHttpRequest(); }else{
/** * IE标准 * @type {ActiveXObject} */ xhr = new ActiveXObject('Microsoft.XMLHTTP') } xhr.onreadystatechange = function () {
if (xhr.readyState == 4){
var status = xhr.status; if (status >= 200 && status < 300 ){
options.success && options.success(xhr.responseText,xhr.responseXML); }else{
options.fail && options.fail(status); } } }; if (options.type == 'GET'){
xhr.open("GET",options.url + p ,options.async); xhr.send(null) }else if (options.type == 'POST'){
/** *打开请求 * */ xhr.open('POST',options.url,options.async); /** * POST请求设置请求头 * */ xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); /** * 发送请求参数 */ xhr.send(params); } } /** * 对象参数的处理 * @param data * @returns {string} */ function getParams(data) {
var arr = []; for (var param in data){
arr.push(encodeURIComponent(param) + '=' +encodeURIComponent(data[param])); } //console.log(arr); arr.push(('randomNumber=' + Math.random()).replace('.','')); //console.log(arr); return arr.join('&'); }

转载于:https://www.cnblogs.com/wangxiaohang/p/7295454.html

你可能感兴趣的文章
团队冲刺04
查看>>
我的Python分析成长之路8
查看>>
泛型在三层中的应用
查看>>
SharePoint2010 -- 管理配置文件同步
查看>>
.Net MVC3中取得当前区域的名字(Area name)
查看>>
获得屏幕像素以及像素密度
查看>>
int与string转换
查看>>
adb命令 判断锁屏
查看>>
推荐一个MacOS苹果电脑系统解压缩软件
查看>>
1035等差数列末项计算
查看>>
CDMA鉴权
查看>>
ASP.NET MVC Identity 兩個多個連接字符串問題解決一例
查看>>
过滤器与拦截器区别
查看>>
第二阶段站立会议7
查看>>
JAVA多线程
查看>>
delphi 更改DBGrid 颜色技巧
查看>>
POJ 2031 Building a Space Station
查看>>
面向对象1
查看>>
任意阶幻方(魔方矩阵)C语言实现
查看>>
织梦教程
查看>>