一、Ajax跨域請求的寫法
Ajax中的跨域請求可以通過XMLHttpRequest對象的open()方法實現,其中要注意的是,跨域請求需要設置請求頭的Origin欄位,並且請求成功時,伺服器需要在響應頭中設置Access-Control-Allow-Origin欄位,對於不支持跨域請求的瀏覽器,需要使用其他方式進行兼容處理。以下為示例代碼:
var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://example.com/api/data',true); xhr.setRequestHeader('Origin', 'http://localhost:8080'); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { console.log(xhr.responseText); } }; xhr.send();
二、JQAjax跨域請求
在jQuery中,跨域請求可以通過jsonp方式實現,也可以通過jQuery.ajax()方法中的設置進行處理,例如:使用xhrFields屬性來設置跨域請求的Cookie傳遞,dataType屬性來設置返回數據類型等,以下為示例代碼:
$.ajax({ url: 'http://example.com/api/data', type: 'GET', crossDomain: true, xhrFields: { withCredentials: true }, dataType: 'json', success: function(response) { console.log(response); }, error: function(xhr, status, error) { console.log(error); } });
三、Ajax跨域請求的處理方式
1. Ajax跨域請求200但沒進error的處理方式
如果Ajax跨域請求200但沒有進入error回調函數,可以根據返回的數據類型進行判斷並處理,例如:
$.ajax({ url: 'http://example.com/api/data', type: 'GET', success: function(response, status, xhr) { if (typeof response === 'string') { response = JSON.parse(response); } console.log(response); } });
2. Ajax跨域請求如何禁止預檢請求
某些情況下,伺服器不支持預檢請求,需要禁止Ajax發出預檢請求,可以設置xhr.setRequestHeader(‘x-requested-with’, ‘XMLHttpRequest’)請求頭來實現,例如:
var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://example.com/api/data',true); xhr.setRequestHeader('Origin', 'http://localhost:8080'); xhr.setRequestHeader('x-requested-with', 'XMLHttpRequest'); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { console.log(xhr.responseText); } }; xhr.send();
3. Ajax跨域請求的解決方案
在瀏覽器中,可以通過JSONP、CORS、代理伺服器等方式進行跨域請求的處理,其中JSONP是比較兼容的解決方案,CORS需要伺服器端的支持,代理伺服器需要單獨搭建,以下為JSONP和CORS的示例代碼:
- JSONP方式的示例代碼:
- CORS方式的示例代碼:
<script> function processData(data) { console.log(data); } var script = document.createElement('script'); script.src = 'http://example.com/api/data?callback=processData'; document.head.appendChild(script); </script>
var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://example.com/api/data',true); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { console.log(xhr.responseText); } }; xhr.withCredentials = true; xhr.send();
四、Ajax跨域請求的原理
Ajax跨域請求的原理在於瀏覽器遵循同源策略,對於不同源的資源訪問進行限制,跨域請求需要伺服器端的支持,通過響應頭中Access-Control-Allow-Origin、Access-Control-Allow-Methods、Access-Control-Allow-Headers、Access-Control-Max-Age等欄位的響應,表示是否允許跨域請求。瀏覽器通過預檢請求(OPTIONS)確認服務端是否允許跨域請求。客戶端可以通過相關配置或使用第三方工具進行跨域請求的處理。
原創文章,作者:ROGL,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/133958.html