zoukankan      html  css  js  c++  java
  • ajax promise

    <script>
    function ajaxPromise(options){
    let {
    type='get',
    url,
    data = {},
    dataType = 'json',
    cache = false // 不缓存
    } = options;
    //data参数处理
    let str = '';
    for(let k in data){
    if(data.hasOwnProperty(k)){
    str += `${k}=${data[k]}&`
    }
    }
    str = str.slice(0,str.length-1);
    //处理 url
    //判断是否是get请求
    let isGet = null;
    if(/get|head|delete/.test(type)){
    isGet = true;
    }else {
    isGet = false;
    }
    if(isGet){ // 是get系列请求
    if(url.indexOf('?') == -1){
    url += `?${str}`;
    }else {
    url = url.replace(/&$/,'');
    url += `&${str}`;
    }
    // cache ? null : url+=`&t=${Math.random()}`;
    cache ? null : url+=`&t=${new Date().getTime()}`;
    }
    return new Promise(function (resolve, reject) {
    //这里边的是做原生ajax;
    let xhr = new XMLHttpRequest();
    xhr.open(type,url);// 默认做成异步
    xhr.onreadystatechange = function () {
    if(xhr.readyState == 4 && /^2d{2}|304/.test(xhr.status)){
    //成功获取数据
    //根据不同数据类型处理数据
    let data = null;
    switch (dataType){
    case 'json':
    data = JSON.parse(xhr.responseText);
    break;
    case 'xml':
    data = xhr.responseXML;
    break;
    default:
    data = xhr.responseText;
    }
    resolve(data);
    }
    if(xhr.readyState == 4 && /^[45]d{2}/.test(xhr.status)){
    //获取失败;
    reject(xhr);
    }
    };
    if(!isGet){
    xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
    }
    xhr.send(str);
    })
    }


    ajaxPromise({
    url:'./1.json',
    data:{q:1},
    }).then((data)=>{
    console.log(data);
    data.push(1234);
    return data;
    }).then((data)=>{
    console.log(data);
    }).catch(()=>{

    });
    </script>
  • 相关阅读:
    20102012一年的学习总结
    Excel 强大的数据操纵能力
    如何提高软件可维护性
    软件工程中的图
    软件工程需求规格说明书
    Windows下启动和停止命令的bat文件
    为何Spring MVC可获取到方法参数名,而MyBatis却不行?【享学Spring MVC】
    crontab
    (转)windows phone7 练习作品(2)
    (转)Windows Phone 资源文件
  • 原文地址:https://www.cnblogs.com/xieting123/p/9625271.html
Copyright © 2011-2022 走看看