Ajax 設置Access-Control-Allow-Origin實現跨域訪問

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
這裏寫圖片描述

server.php 路徑:http://www.server.com/server.php

這裏寫圖片描述

Access-Control-Allow-Origin:* 表示允許任何域名跨域訪問
如果需要指定某域名才允許跨域訪問,只需把Access-Control-Allow-Origin:*改爲Access-Control-Allow-Origin:允許的域名
例如:header(‘Access-Control-Allow-Origin:http://www.client.com‘);
如果需要設置多個域名允許訪問,這裏需要用php處理一下
例如允許 www.client.com 與 www.client2.com 可以跨域訪問
server.php 修改爲:

這裏寫圖片描述

發佈了140 篇原創文章 · 獲贊 51 · 訪問量 18萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章