做過web前端人都知道,經(jīng)常會(huì)有ajax跨域問題,下面列舉我經(jīng)常使用的解決辦法
第一種:使用jsonp,jQuery的ajax方法支持jsonp,但是最大的缺點(diǎn)就是只支持get方式,而且服務(wù)端也要修改
客戶端 test.html代碼
<!DOCTYPE html>
<html>
<head>
<title>工作端</title>
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<meta charset="utf-8">
<script src="jquery-1.10.2.min.js"></script>
<style>
</style>
</head>
<body>
<input type="button" value="測(cè)試" id="demo">
<div id="result">
</div>
<script>
$(document).ready(function() {
var cache = {};
$("#demo").click(function(){
$.ajax({
type : "get",
async:false,
data:{"name":"test001","age":"100"},
url : "http://192.168.10.111/server.php", //跨域請(qǐng)求的URL
dataType : "jsonp",
//傳遞給請(qǐng)求處理程序,用以獲得jsonp回調(diào)函數(shù)名的參數(shù)名(默認(rèn)為:callback)
jsonp: "callback",
//自定義的jsonp回調(diào)函數(shù)名稱,默認(rèn)為jQuery自動(dòng)生成的隨機(jī)函數(shù)名
jsonpCallback:"success_jsonpCallback",
//成功獲取跨域服務(wù)器上的json數(shù)據(jù)后,會(huì)動(dòng)態(tài)執(zhí)行這個(gè)callback函數(shù)
success : function(json){
alert(json,name);
}
});
});
})
</script>
</body>
</html>
第二種:nginx反向代理,我的nginx版本nginx-1.10.0
首先在 conf\apiserver-reverse-proxy-conf\bingli\main.conf ,沒有相關(guān)目錄和文件就新
location ~* ^/uc/.*{
proxy_set_header Host $host;
proxy_set_header X-Real-Ip $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://192.168.10.111:8080;
}
然后在nginx主配置文件添加加粗內(nèi)容,即把代理文件加載進(jìn)來(lái)
location / {
root html;
index index.html index.htm;
}
include apiserver-reverse-proxy-conf/bingli/main.conf;
重啟nginx,之后ajax發(fā)請(qǐng)求到
http://localhost/uc/aa
http://localhost/uc/bb?token=xxxx
都會(huì)被轉(zhuǎn)發(fā)到
http://192.168.10.111:8080/uc/aa
http://192.168.10.111:8080/uc/bb?token=xxxx