原生JS实现移动端APP ajax功能

/* 封装ajax函数
 * @param {string}opt.type http连接的方式,包括POST和GET两种方式
 * @param {string}opt.url 发送请求的url
 * @param {boolean}opt.async 是否为异步请求,true为异步的,false为同步的
 * @param {object}opt.data 发送的参数,格式为对象类型
 * @param {function}opt.success ajax发送并接收成功调用的回调函数
 * @param {function}opt.error ajax发送并接收失败调用的回调函数
 */
function ajax(opt) {
    opt = opt || {};
    opt.method = opt.method.toUpperCase() || 'POST';
    opt.url = opt.url || '';
    opt.async = opt.async || true;
    opt.data = opt.data || null;
    opt.success = opt.success || function () {};
    opt.error = opt.error || function () {};
    var xhr = new plus.net.XMLHttpRequest();
    xhr.onloadstart = function(){
    	console.log("开始请求")
    }
    xhr.onprogress = function(){
    	console.log("请求传输");
    }
    xhr.onabort = function(){
    	console.log("请求中断");
    }
    xhr.onerror = function(){
    	console.log("请求错误")
    }
    xhr.ontimeout = function(){
    	console.log("请求超时")
    }
    xhr.onloadend = function(){
    	console.log("请求结束");
    }
    var params = [];
    for (var key in opt.data){
        params.push(key + '=' + opt.data[key]);
    }
    var postData = params.join('&');
    if (opt.method.toUpperCase() === 'POST') {
        xhr.open(opt.method, opt.url, opt.async);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');
        xhr.send(postData);
    }
    else if (opt.method.toUpperCase() === 'GET') {
        xhr.open(opt.method, opt.url + '?' + postData, opt.async);
        xhr.send();
    }
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            opt.success(eval("("+xhr.responseText+")"));
        }else if(xhr.readyState == 4){
        	console.log(xhr.status)
        	opt.error(xhr.staus);
        }
    };
}

注意:xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');

1.在发起请求时,未加入charset=utf-8有可能造成,前端发送数据的 "编码方式" 与后台接收数据的 "解码方式" 不同,导致访问不到或时间过长

2.有可能遇到跨域问题,可以在java服务器controller中,加入如下代码解决问题

response.setHeader("Access-Control-Allow-Origin", "*");
发布了21 篇原创文章 · 获赞 2 · 访问量 4793

猜你喜欢

转载自blog.csdn.net/qq_21479345/article/details/93540866
今日推荐