ajax封装运用

    技术2022-07-10  81

    /* 请求方式:type 非必传,默认get 请求地址:url 必传 是否异步:async 非必传 设置头请求:contentType 非必传 请求数据:data 非必传 */ ajax({ 'url': 'b.txt', 'success': function(res){ console.log(res); // 将字符串计算: eval(要转的数据) console.log(eval('3+2')); // 在js中{}中的默认就是完整的代码块 // console.log('(' + eval(res) + ')'); console.log(JSON.parse(res));//转换为Json类型 json数据的格式, 键值一一相对的键值对 /* json数据的格式: 1. [] {} 2. 所有的属性名和字符全部加上双引号 3. 多余的符号不要加 4. 文件名以.json结尾 5. 转成js数据: JSON.parse(要转换的数据) 转成json数据: JSON.stringify(要转换的数据) */ var r = JSON.parse(res); console.log(JSON.stringify(r));//转换为字符串 } }); function ajax(json) { console.log(json.success); json.type = json.type ? json.type : 'get'; json.async = json.async == false ? false : true; json.contentType = json.contentType ? json.contentType : 'application/x-www-form-urlencoded'; json.data = json.data ? json.data : ''; var ajax = new XMLHttpRequest(); // 判断是get还是post请求 if (json.type.toLowerCase() == 'post') { ajax.open('post', json.url, json.async); ajax.setRequestHeader('Content-type', json.contentType + ';charset=utf-8'); ajax.send(json.data); } else { ajax.open('get', json.url + '?' + json.data, json.async); ajax.send(); } ajax.onreadystatechange = function () { if (ajax.readyState == 4 && ajax.status == 200) { json.success(ajax.response); } } }
    Processed: 0.011, SQL: 9