网站首页 > 技术文章 正文
在网上查看了很多js的ajax封装函数
发现大部分都没有实现跨域请求
所以跨域请求浏览器就会提示:No 'Access-Control-Allow-Origin' header is present on the requested resource.
于是封装了一个跨域请求的ajax函数:
js代码:
[html] view plain copy
- function ajax(obj) {
- // 对实参处理
- obj = obj || {};
- // 定义局部变量
- var xmlhttp, type, url, async, dataType, data;
- // 默认type为GET
- type = trim(obj.type).toUpperCase() || 'GET';
- // 接口
- url = trim(obj.url) || window.location.href;
- // 默认为异步请求
- async = obj.async || true;
- // 设置跨域
- dataType = trim(obj.dataType).toUpperCase() || 'HTML';
- // 发送参数
- data = obj.data || {};
- // 删除左右空格
- function trim(str) {
- return str.replace(/^\s+|\s+$/g, "");
- };
- // 定义格式化参数函数
- var formatParams = function() {
- if (typeof(data) == "object") {
- var str = "";
- for (var pro in data) {
- str += pro + "=" + data[pro] + "&";
- }
- data = str.substr(0, str.length - 1);
- }
- if (type == 'GET' || dataType == 'JSONP') {
- if (url.lastIndexOf('?') == -1) {
- url += '?' + data;
- } else {
- url += '&' + data;
- }
- }
- }
- // 第一步,创建xmlhttprequest对象用来和服务器交换数据。
- if (window.XMLHttpRequest) {
- //Chrome || Firefox
- xmlhttp = new XMLHttpRequest();
- } else {
- //IE
- xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
- }
- // 跨域请求
- if (dataType == 'JSONP') {
- if (typeof(obj.beforeSend) == 'function') obj.beforeSend(xmlhttp);
- var callbackName = ('jsonp_' + Math.random()).replace(".", "");
- var oHead = document.getElementsByTagName('head')[0];
- data.callback = callbackName;
- var ele = document.createElement('script');
- ele.type = "text/javascript";
- ele.onerror = function() {
- console.log('failed');
- obj.error && obj.error("failed");
- };
- oHead.appendChild(ele);
- window[callbackName] = function(json) {
- oHead.removeChild(ele);
- window[callbackName] = null;
- obj.success && obj.success(json);
- };
- formatParams();
- ele.src = url;
- return;
- } else {
- formatParams();
- // 第二步,打开链接
- xmlhttp.open(type, url, async);
- // 设置响应头
- xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
- if (typeof(obj.beforeSend) == 'function') obj.beforeSend(xmlhttp);
- // 第三步,发送请求
- xmlhttp.send(data);
- // 第四步,响应处理
- xmlhttp.onreadystatechange = function() {
- if (xmlhttp.status != 200) {
- console.log(xmlhttp.status + 'failed');
- obj.error && obj.error(xmlhttp.status + 'failed');
- return;
- }
- if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
- if (dataType == 'JSON') {
- try {
- res = JSON.parse(xmlhttp.responseText);
- } catch (e) {
- console.log('json格式错误');
- obj.error('json格式错误');
- }
- } else if (dataType == 'XML') {
- res = xmlhttp.responseXML;
- } else {
- res = xmlhttp.responseText;
- }
- obj.success && obj.success(res);
- }
- }
- }
- }
使用示例:
[html] view plain copy
- ajax({
- url: '',
- type: 'get',
- dataType: 'jsonp',
- success: function(data) {
- },
- error: function() {
- }
- })
猜你喜欢
- 2024-09-12 不得不佩服,美观小巧的网页内容编辑器——ContentTools
- 2024-09-12 监听设备方向变化?分享 1 段优质 JS 代码片段!
- 2024-09-12 一分钟了解ajax。(一分钟了解网络广告)
- 2024-09-12 Jquery一个简单的注册验证(jquery注册点击事件)
- 2024-09-12 [前端请求]Ajax知识点 Jquery接口封装 fetch原生js请求
- 2024-09-12 JQuery笔记(下)(jquery gt)
- 2024-09-12 Vue.js 快速上手(vue.js怎么学)
- 2024-09-12 Ajax 的全面总结(ajax概述)
- 2024-09-12 html file选择文件一次之后就失效了怎么办
- 2024-09-12 jQuery入门2(jquery入门教程)
- 最近发表
- 标签列表
-
- cmd/c (64)
- c++中::是什么意思 (83)
- 标签用于 (65)
- 主键只能有一个吗 (66)
- c#console.writeline不显示 (75)
- pythoncase语句 (81)
- es6includes (73)
- sqlset (64)
- windowsscripthost (67)
- apt-getinstall-y (86)
- node_modules怎么生成 (76)
- chromepost (65)
- c++int转char (75)
- static函数和普通函数 (76)
- el-date-picker开始日期早于结束日期 (70)
- localstorage.removeitem (74)
- vector线程安全吗 (70)
- & (66)
- java (73)
- js数组插入 (83)
- linux删除一个文件夹 (65)
- mac安装java (72)
- eacces (67)
- 查看mysql是否启动 (70)
- 无效的列索引 (74)