分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 软件开发

简单封装一个ajax插件

发布时间:2023-09-06 02:31责任编辑:林大明关键词:暂无标签
function ajax(options) { ???options = options || {}; ???options.type = options.type || ‘get‘; ???options.type = options.data || {}; ???options.dataType = options.dataType || ‘text‘; ???//IE6以下无法使用 ???let xhr = new XMLHttpRequest(); ???// 数据修改 ???let arr = []; ???for (let name in options.data) { ???????arr.push(`${name}=${options.data[name]}`) ???} ???let strData = arr.join(‘&‘); ???if (options.type == ‘post‘) { ???????xhr.open(‘post‘, options.url, true); ???????xhr.setRequestHeader(‘content-type‘, ‘application/x-www-form-urlencoded‘) ???????xhr.send(strData); ???} else { ???????xhr.open(‘get‘, options.url + ‘?‘ + strData, true); ???????xhr.send(); ???} ???xhr.onreadystatechange = function () { ???????if (xhr.readyState == 4) { ???????????if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) { ???????????????let data = xhr.responseText; ???????????????switch (options.dataType) { ???????????????????case ‘json‘: ???????????????????????if (window.JSON && JSON.parse) { ???????????????????????????data = JSON.parse(data); ???????????????????????} else { ???????????????????????????data = eval(‘(‘ + str + ‘)‘) ???????????????????????} ???????????????????????break; ???????????????????case ‘xml‘: ???????????????????????data = xhr.responseXML; ???????????????????????break ???????????????} ???????????????options.success && options.success(data); ???????????} else { ???????????????options.error && options.error() ???????????} ???????} ???}}

简单封装一个ajax插件

原文地址:https://www.cnblogs.com/yang656/p/10336003.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved