实战演练--js实现在网页间传递数据

php是最好的语言
php是最好的语言 原创
2018-08-10 16:16:37 2277浏览

1.估计很少人知道HTML5 APIS里有一个window.postMessage API。window.postMessage的功能是允许程序员跨域在两个窗口/frames间发送数据信息。基本上,它就像是跨域的AJAX,但不是浏览器跟服务器之间交互,而是在两个客户端之间通信。让我们来看一下window.postMessage是如何工作的。除了IE6、IE7之外的所有浏览器都支持这个功能。

2. 先创建一个index.html 文件。 (在测试的的时候必须用服务器测试呀 ; file:// 这样地址的开头是错误的不准许访问发送(因为window.postMessage这个方法是跨域 跟 ajax 差不多 所以很相似))

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
     body,p{
        margin: 0px;
        padding: 0px;
     }
    </style>
</head>
<body>
    
    <script>
        //弹出一个新窗口
        var domain = 'http://localhost:8080/chenzhenhua/';
        var myPopup = window.open(domain+'lister.html','myWindow');//打开另一个网址
        //  var array=["100","liyoubing","200"];
        var array=[{"姓名":"李友冰"},{"性别":"男"}]

        //周期性的发送消息
        setInterval(function(){
           //var message = 'Hello!  The time is: ' + (new Date().getTime());
          //  console.log('blog.local:  sending message:  ' + message);
             //array:发送消息de数据,domain: 是url;
            myPopup.postMessage(array,domain);
        },6000);
    </script>
</body>
</html>

3. 在创建 lister.html 文件 代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script>
         //监听消息反馈
       window.addEventListener('message',function(event) {
            console.log(event);
            if(event.origin !== 'http://localhost:8080') return;
            console.log('received response:  ',event.data);

        },false);
    </script>
</body>
</html>

4.结果如下:

1.png 相关推荐:

javascript实现html页面之间参数传递的四种方法实

html怎样实现页面跳转时传递参数

以上就是实战演练--js实现在网页间传递数据的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。