封装ajax

来源:互联网 发布:闲鱼淘宝介入支持卖家 编辑:程序博客网 时间:2024/06/05 17:54
/** @Author: 动如脱too* @Date:   2017-07-03 17:00:12* @Last Modified time: 2017-08-04 09:35:43* @Email:772798270@qq.com*//*调用ajax    ajax({        url:'发送请求的url',        type:'post/get',           \\(option,请求的类型,默认是get)        async:true/false,          \\(option,是否为异步请求,默认是true)        data:object,               \\(option,发送请求的参数,格式为对象或字符串)        dataType:'text/XML/JSON', \\(option,返回的数据类型,默认是text)        success:function(){}       \\(potion,ajax发送并接受成功调用的回调函数)    }) */'use strict';function ajax(opt) {    // 初始化参数、设置默认值    if(!opt.url){        alert('请输入正确的URL');        return;    }    var url = opt.url;    var type = opt.type || 'GET';    var async = opt.async===undefined?true:opt.async;    var data = opt.data || '';    var dataType = opt.dataType || 'TEXT';    var success = opt.success || function () {};    if(typeof data == 'object'){        // 将json格式的data拼接成字符串        var arr = [];        for(var key in data){            arr.push(key+'='+data[key]);        }        data = arr.join('&');    }    // 创建一个ajax对象    // 注意:如果这样写 var xhr = new XMLHttpRequest() || xhr = new ActiveXObject('Microsoft.XMLHTTP')    // 当XMLHttpRequest()不存在时会产生一个语法错误    if (XMLHttpRequest) {        var xhr = new XMLHttpRequest();  }else {        var xhr = new ActiveXObject('Microsoft.XMLHTTP');  }     // 设置请求类型并发送请求    if(type.toUpperCase() == 'GET'){        xhr.open(type,url+'?'+data,async);        xhr.send();    }    if(type.toUpperCase() == 'POST'){        xhr.open(type,url,async);     xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');     xhr.send(data);    }    // 监听服务器响应    xhr.onreadystatechange = function(){        if (xhr.readyState == 4 ) {            if(xhr.status == 200){                if(dataType.toUpperCase() == 'TEXT'){                    success(xhr.responseText)                }else if(dataType.toUpperCase() =='XML'){                    success(xhr.responseXML)                }else if(dataType.toUpperCase() =='JSON'){                    // JSON.parse()将json格式的字符串转化为json                    success(JSON.parse(xhr.response));                }            }else if(xhr.status==404){                alert('请求失败');            }    }    }}
原创粉丝点击