天天看點

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

繼續閱讀