用iframe設定代理解決ajax跨域請求問題_AJAX相關

來源:互聯網
上載者:User
今天在項目中需要做遠端資料載入並渲染頁面,直到開發階段才意識到ajax跨域請求的問題。於是想用代理的方式來解決這個跨域問題。

什麼是跨域?

簡單的來說,出於安全方面的考慮,頁面中的JavaScript無法訪問其他伺服器上的資料,即“同源策略”。而跨域就是通過某些手段來繞過同源策略限制,實現不同伺服器之間通訊的效果。

方案:在伺服器端建立一個靜態代理頁面,在用戶端用iframe調用這個代理,然後通過iframe的document.getElementById("proxy").contentWindow對象來請求ajax。

伺服器端的代理頁面:
複製代碼 代碼如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax跨域</title>
<script src="js/jquery-1.6.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
document.domain = 'xxx.com';
</script>
</head>
<body>
</body>
</html>

用戶端ajax的調用程式碼範例:
複製代碼 代碼如下:

<iframe src="http://weixin.goumin.com/proxy.html" id="proxy" style="display:none;" onload="loadDefaultData();"></iframe>
<script type="text/javascript">
document.domain = "xxx.com";
function loadDefaultData(){
var iframe_jquery = document.getElementById("proxy").contentWindow.$;
iframe_jquery.ajax({
type: "POST",
url:""+Math.random(),
data:{},
async:false,
dataType:'json',
success:function(data){
alert(data);
}
});
}
</script>

url:""+Math.random(),

請注意加紅的url這行,用一個隨機函數來解決瀏覽器緩衝的問題。讓每一次請求的url不一樣。
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.