记录大数据埋点遇到的XMLHttpRequest的坑

需求

一个前后不分离的老项目,需要进行数据埋点.以为很简单.在浏览器打印出了$.ajax.,于是高高兴兴的用Ajax请求写完才发现了深坑.请求失败.才发现他们项目里面重新定义 ajax 请求 .与原本的请求格式都不一致.

尝试

1 参照他们的ajax 请求方式进行了编写,还是无效.然后想起他们的 请求并没有带域名请求应该是构建了公共的 url.如果还是使用他们的格式请求显然行不通.

2 翻了下,发现可以使用 $.post 进行请求. 可惜报403.显示跨域.但其他系统都可以正常的跨域使用了. 此处也设置了 $.support.cors也是为true. 使用 $.crossDomain 也是一样
在这里插入图片描述
3 上面的没法子.然后尝试了下 XMLHttpRequest. 结果返回结果提示参数有误

function basePoint () {
	var xhr = new XMLHttpRequest(); 
	 if (xhr.withCredentials === undefined) {  
              return;  
        }
     xhr.withCredentials = true;
	xhr.open('POST', 'urlurl', true);
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xhr.send({
		appSecrect: window.appSecrect,
		appName: window.appName,
		userName: window.userName
	});
	xhr.onreadystatechange = function () {
			if (xhr.readyState === 4 && xhr.status === 200) {
					var pointStatus = JSON.parse(xhr.responseText);
					console.log(pointStatus)
				}
			}
		};
basePoint();

然后搜了下 send 的使用, 因为其他的项目使用了 xhr 的send 传对象或者json 都是有效的.也没往这方面想.看了才发现可能是 参数问题.更改传参之后.就可以正常的使用了
在这里插入图片描述

解决

function basePoint () {
	var xhr = new XMLHttpRequest();
	xhr.open('POST', 'urlurl', true);
	xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xhr.send("appSecrect=" + window.appSecrect+ "&userName=" + window.userName + "&appName=" + window.appName);
	xhr.onreadystatechange = function () {
				if (xhr.readyState === 4 && xhr.status === 200) {
					var pointStatus = JSON.parse(xhr.responseText);
					console.log(pointStatus)
				}
			}
		};
basePoint();

感觉对于xhr还是不熟.所以后续学习了下,这篇文章写的很好

	https://segmentfault.com/a/1190000004322487#item-5-13

拓展:

1 XMLHttpRequest对象与ajax 的关系: 我们使用XMLHttpRequest对象来发送一个Ajax请求。
2 XMLHttpRequest有 Level 1 / Level 2 : Level 1 是不支持跨域的
3 设置  xhr.withCredentials = true; 允许跨域
4 导出  Excel 文件时. responseType 设置为 arrayBuffer(缓冲数组)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章