前端跨域雜談,跨域雜談

來源:互聯網
上載者:User

前端跨域雜談,跨域雜談
1、前端跨域之表單(post)項目需求,需要跨域向另一台伺服器傳送大量值,從ajax角度跨域是get方式,基於此,方案採用構造<form>表單,通過action發送到對方伺服器,對方伺服器需要做一些配合。
發送方post.html
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0,minimum-scale=1.0, user-scalable=no" name="viewport">
    </head>
    <body>
        <script>
            function postcallback(data){
            }
        </script>
        <form action="http://10.16.92.34:81/xampp/index.php" method="post" target="ifr-result">
            <input type="text" name="data" />
            <input type="submit" value="提交" />
        </form>
        <iframe name="ifr-result"></iframe>
    </body>
</html>
對方伺服器接收index.php<?php
    $data = '{"ret": 0, "msg": "ok"}';
    // 結果跳轉到當前域執行
    header("Location: http://10.16.92.34:81/xampp/ifr-callback.php?data=".urlencode($data));
重新導向到同網域名稱服務 (DNS)內部處理 ifr-callback.php<?php
header('Content-type: text/javascript');
echo '<script>';
//回調原頁面上函數處理返回結果
echo 'parent.postcallback(' .$_GET['data']. ');';
echo '</script>';
2、前端跨域之CORS (post)CORS跨域資源共用:定義一種瀏覽器和伺服器互動的方式來確定是否允許跨域請求。
詳細內容:前端代碼:post.html<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0,minimum-scale=1.0, user-scalable=no" name="viewport">
    </head>
    <body>
        <script>
            var xhr = new XMLHttpRequest();
            xhr.open("GET", "http://10.16.92.34:81/xampp/index.php", true);
            xhr.send();
            xhr.onreadystatechange = ajaxCallback;
            function ajaxCallback(data) {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    console.log(data);
                    console.log(data.srcElement.responseText);
                }
            }
        </script>
    </body>
</html>
服務端對於CORS的支援,主要就是通過設定Access-Control-Allow-Origin來進行的。index.php<?php
    header("Access-Control-Allow-Origin:*");
    $data = '{"ret": 0, "msg": "ok"}';
    // 結果跳轉到當前域執行
    header("Location: http://10.16.92.34:81/xampp/ifr-callback.php?data=".urlencode($data));
ifr-callback.php<?php
header("Access-Control-Allow-Origin:*");
header('Content-type: text/json');
//回調原頁面上函數處理返回結果
echo $_GET['data'];
3、H5跨域postMessage
a)在Web Workers中使用postMessage和onmessagestep1:準備一個主線程頁面work.html<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test Web worker</title>
<script type="text/JavaScript">
     function init() {
         var worker = new Worker('http://res.imtt.qq.com/cloud_based_adp/sdktagdemo/js/compute.js');
         //event 參數中有 data 屬性,就是子線程中返回的結果資料
         worker.onmessage= function (event) {
             // 把子線程返回的結果添加到 div 上
             document.getElementById("result").innerHTML +=
                event.data + "<br/>";
         };
     }
</script>
</head>
<body onload="init()">
<div id="result"></div>
</body>
</html>
step2:向主線程發送資訊-compute.jsvar i = 0;
function timedCount() {
     for (var j = 0, sum = 0; j < 100; j++) {
         for (var i = 0; i < 100000000; i++) {
             sum += i;
         }
     }
     // 調用 postMessage 向主線程發送訊息
     postMessage(sum);
}
postMessage("Before computing,"+new Date());
timedCount();
postMessage("After computing,"+new Date());
b)跨域文檔通訊使用postMessage和onmessage
step1:假設在A域構造一個頁面cross-domain.html頁面(通過iframe嵌入一個子頁面,調用postMessage方法發送資料) <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Test Cross-domain communication using HTML5</title>
<script type="text/JavaScript">
     function sendIt(){
          // 通過 postMessage 向子視窗發送資料
          document.getElementById("otherPage").contentWindow
               .postMessage(
                    document.getElementById("message").value,
                    "http://10.16.92.34:81"
               );
     }
</script>
</head>
<body>
     <!-- 通過 iframe 嵌入子頁面 -->
     <iframe src="http://10.16.92.34:81/xampp/other-domain.html"
                    id="otherPage"></iframe>
     <br/><br/>
     <input type="text" id="message"><input type="button"
               value="Send to child.com" onclick="sendIt()" />
</body>
</html>
step2:B域頁面other-domain.html子視窗中監聽onmessage事件,顯示父視窗發送來的資料<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Web page from child.com</title>
<script type="text/JavaScript">
     //event 參數中有 data 屬性,就是父視窗發送過來的資料
     window.addEventListener("message", function( event ) {
         // 把父視窗發送過來的資料顯示在子視窗中
       document.getElementById("content").innerHTML+=event.data+"<br/>";
     }, false );

</script>
</head>
<body>
     Web page from http://10.16.92.34:81
     <div id="content"></div>
</body>

</html>

操作參考圖:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.