本文主要是介绍521源码-免费源码下载-免费学习教程-常见的原生js封装ajax,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
更多 网站源码 学习教程 游戏源码,请点击👉-521源码-👈获取最新资源
请看以下案例:
function ajax(options) {var xhr = null;var type = 'GET';var params = formsParams(options.data);if(typeof options.type != 'undefined'){type = options.type.toUpperCase();}//创建对象if (window.XMLHttpRequest) {xhr = new XMLHttpRequest();} else {xhr = new ActiveXObject("Microsoft.XMLHTTP");}if (typeof options.async == "undefined") {options.async = true;}// 处理请求成功的回调函数xhr.onload = function(){if (xhr.status >= 200 && xhr.status < 300) {if (typeof options.datatype == "undefined" || options.datatype == "json") {if(typeof options.success === 'function'){options.success(JSON.parse(xhr.responseText));}} else {if(typeof options.success === 'function'){options.success(xhr.responseText);}}} else {if(typeof options.error === 'function'){options.error(xhr.statusText);}}}// 处理请求错误的回调函数xhr.onerror = function() {if(typeof options.error === 'function'){options.error(xhr.statusText);}}// 设置请求头部if (options.headers) {for (var header in options.headers) {xhr.setRequestHeader(header, options.headers[header]);}}// 设置请求方法、URL、是否异步、发送请求if (type == "GET") {xhr.open(type, options.url + "?" + params, options.async);xhr.send(null);} else if (type == "POST") {xhr.open(type, options.url, options.async);xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");xhr.send(params);}function formsParams(data) {var arr = [];for (var prop in data) {arr.push(prop + "=" + data[prop]);}return arr.join("&");} }// 使用 ajax({url: "api.php",// 请求地址type: "POST",// 请求方式async: true,// 同步:false,异步:true,默认为truedatatype: "json",// 返回数据的格式,"json","text",默认为jsonheaders: {},// 设置请求头部,{"token": "123456"}data: {// post数据code: "s2sdd",link: location.href},success: function (res) {// 处理请求成功console.log(res);},error: function (res) {// 处理请求错误console.log(res);} })
这篇关于521源码-免费源码下载-免费学习教程-常见的原生js封装ajax的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!