前端跨域杂谈

来源:互联网 发布:51信用卡待遇 知乎 编辑:程序博客网 时间:2024/06/17 13:00
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));

重定向到同域名服务内部处理 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和onmessage
step1:准备一个主线程页面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.js
var 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>

操作参考图:

0 0
原创粉丝点击