1. 程式人生 > >ajax完美解決跨域問題(jsonp、nginx反向代理)

ajax完美解決跨域問題(jsonp、nginx反向代理)

做過web前端人都知道,經常會有ajax跨域問題,下面列舉我經常使用的解決辦法

第一種:使用jsonp,jquery的ajax方法支援jsonp,但是最大的缺點就是隻支援get方式,而且服務端也要修改

客戶端 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="測試" 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", //跨域請求的URL
			dataType : "jsonp",
			//傳遞給請求處理程式,用以獲得jsonp回撥函式名的引數名(預設為:callback)
			jsonp: "callback",
			//自定義的jsonp回撥函式名稱,預設為jQuery自動生成的隨機函式名
			jsonpCallback:"success_jsonpCallback",
				//成功獲取跨域伺服器上的json資料後,會動態執行這個callback函式
			success : function(json){ 
				alert(json,name);
			}
		});
	});
})
</script>
</body>
</html>

server.php程式碼
<?php
$arr['id']=100;
$arr['name']="小網";
$data[]=$arr;
$arr['id']=200;
$arr['name']="阿里";
$data[]=$arr;
$data=json_encode($data);
$callback = $_GET['jsoncallback'];
echo $callback."(" .$data.")";

第二種:nginx反向代理,我的nginx版本nginx-1.10.0

首先在 conf\apiserver-reverse-proxy-conf\bingli\main.conf ,沒有相關目錄和檔案就新建

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主配置檔案新增加粗內容,即把代理檔案載入進來
location / {
            root   html;
            index  index.html index.htm;
        }
include apiserver-reverse-proxy-conf/bingli/main.conf;

重啟nginx,之後ajax發請求到

http://localhost/uc/aa
http://localhost/uc/bb?token=xxxx
都會被轉發到
http://192.168.10.111:8080/uc/aa
http://192.168.10.111:8080/uc/bb?token=xxxx