原生js封裝ajax,實現跨域請求

描述:

須要ajax跨域請求,用cors跨域方案。
服務端設置:html

header('Access-Control-Allow-Origin: http://front.ls-la.me');
header('Access-Control-Allow-Headers: X-Requested-With');

 

設置了:

後端須要的頭信息,原生ajax以表單方式post提交數據,json數據data轉換成key1=val1&key2=val2 的字符串格式ajax

 1 var ajaxHdFn = function(uri, data, cb) {
 2   var getXmlHttpRequest = function() {
 3     if (window.XMLHttpRequest) {
 4       //主流瀏覽器提供了XMLHttpRequest對象
 5       return new XMLHttpRequest();
 6     } else if (window.ActiveXObject) {
 7       //低版本的IE瀏覽器沒有提供XMLHttpRequest對象
 8       //因此必須使用IE瀏覽器的特定實現ActiveXObject
 9       return new ActiveXObject("Microsoft.XMLHttpRequest");
10     }
11 
12   };
13   var xhr = getXmlHttpRequest();
14   xhr.onreadystatechange = function() {
15     console.log(xhr.readyState);
16     if (xhr.readyState === 4 && xhr.status === 200) {
17       //獲取成功後執行操做
18       //數據在xhr.responseText
19       var resJson = JSON.parse(xhr.responseText)
20       cb(resJson);
21     }
22   };
23   xhr.open("post", uri, true);
24   xhr.setRequestHeader("DeviceCode", "56");
25   xhr.setRequestHeader("Source", "API");
26   xhr.setRequestHeader("Authentication", "72b32a1f754ba1c09b3695e0cb6cde7f");
27   xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
28   var dataStr = '';
29   for (var i in data) {
30     if (dataStr) {
31       dataStr += '&';
32     }
33     dataStr += i + '=' + data[i];
34   }
35   xhr.send(dataStr);
36 };

 

跨域相關內容

CORS跨域的常見問題以及先後端的設置:json

《Ajax——CORS跨域調用REST API 的常見問題以及先後端的設置》後端

 

data = JSON.stringify(data);
xhr.setRequestHeader("Content-Type","application/json");

這樣設置,能夠直接傳json字符串給後端。後端也要作相應處理。跨域

相關文章
相關標籤/搜索