ajax 设置Access-Control-Allow-Origin实现跨域访问
版權聲明:本文為博主原創文章,未經博主允許不得轉載。如需轉載可私信或關注公眾號fdipzone-idea與我聯系。 https://blog.csdn.net/fdipzone/article/details/46390573
ajax跨域訪問是一個老問題了,解決方法很多,比較常用的是JSONP方法,JSONP方法是一種非官方方法,而且這種方法只支持GET方式,不如POST方式安全。
即使使用jquery的jsonp方法,type設為POST,也會自動變為GET。
官方問題說明:
“script”: Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, “_=[TIMESTAMP]“, to the URL unless the cache option is set to true.Note: This will turn POSTs into GETs for remote-domain requests.
如果跨域使用POST方式,可以使用創建一個隱藏的iframe來實現,與ajax上傳圖片原理一樣,但這樣會比較麻煩。
因此,通過設置Access-Control-Allow-Origin來實現跨域訪問比較簡單。
例如:客戶端的域名是www.client.com,而請求的域名是www.server.com
如果直接使用ajax訪問,會有以下錯誤
XMLHttpRequest cannot load http://www.server.com/server.php. No 'Access-Control-Allow-Origin' header is present on the requested resource.Origin 'http://www.client.com' is therefore not allowed access.
在被請求的Response header中加入
// 指定允許其他域名訪問
header('Access-Control-Allow-Origin:*');
// 響應類型
header('Access-Control-Allow-Methods:POST');
// 響應頭設置
header('Access-Control-Allow-Headers:x-requested-with,content-type');
就可以實現ajax POST跨域訪問了。
代碼如下:
client.html 路徑:http://www.client.com/client.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
?<head>
? <meta http-equiv="content-type" content="text/html;charset=utf-8">
? <title> 跨域測試 </title>
? <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
?</head>
?
?<body>
? ? <div id="show"></div>
? ? <script type="text/javascript">
? ? $.post("http://www.server.com/server.php",{name:"fdipzone",gender:"male"})
? ? ? .done(function(data){
? ? ? ? document.getElementById("show").innerHTML = data.name + ' ' + data.gender;
? ? ? });
? ? </script>
?</body>
</html>
來源:https://blog.csdn.net/fdipzone/article/details/46390573/
總結
以上是生活随笔為你收集整理的ajax 设置Access-Control-Allow-Origin实现跨域访问的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 蚂蚁信用700有什么用
- 下一篇: vue axios 配置上服务器后报错'