ajax跨域訪問是一個老問題了,解決方法不少,比較經常使用的是JSONP方法,JSONP方法是一種非官方方法,並且這種方法只支持GET方式,不如POST方式安全。javascript
即便使用jquery的jsonp方法,type設爲POST,也會自動變爲GET。
php
官方問題說明:
html
「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.
java
若是跨域使用POST方式,可使用建立一個隱藏的iframe來實現,與ajax上傳圖片原理同樣,但這樣會比較麻煩。
jquery
所以,經過設置Access-Control-Allow-Origin來實現跨域訪問比較簡單。
ajax
例如:客戶端的域名是www.client.com,而請求的域名是www.server.com
json
若是直接使用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中加入
app
[php] view plain copy
// 指定容許其餘域名訪問
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
[html] view plain copy
<!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>
server.php 路徑:http://www.server.com/server.php
[php] view plain copy
<?php
$ret = array(
'name' => isset($_POST['name'])? $_POST['name'] : '',
'gender' => isset($_POST['gender'])? $_POST['gender'] : ''
);
header('content-type:application:json;charset=utf8');
header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Methods:POST');
header('Access-Control-Allow-Headers:x-requested-with,content-type');
echo json_encode($ret);
?>
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 修改成
[php] view plain copy
<?php
$ret = array(
'name' => isset($_POST['name'])? $_POST['name'] : '',
'gender' => isset($_POST['gender'])? $_POST['gender'] : ''
);
header('content-type:application:json;charset=utf8');
$origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : '';
$allow_origin = array(
'http://www.client.com',
'http://www.client2.com'
);
if(in_array($origin, $allow_origin)){
header('Access-Control-Allow-Origin:'.$origin);
header('Access-Control-Allow-Methods:POST');
header('Access-Control-Allow-Headers:x-requested-with,content-type');
}
echo json_encode($ret);
?>