記錄大數據埋點遇到的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(緩衝數組)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章