JS实现跨域页面传值
2017-12-25 16:59
183 查看
一、背景介绍
页面1中有一个按钮,希望实现点击按钮打开页面2。
页面2进行一系列操作后,点击该页面确定按钮后关闭页面,同时返回值到页面1
ps:页面1与页面2位于不同服务器,即跨域
二、实现
使用postMessage()实现上述功能。
1.页面1上的代码:
2.页面2上返回值代码
归纳实现操作就是:
1.页面1使用window.open(url)函数打开页面2
2.页面2使用window.opener.postMessage(param1,param2)返回消息到页面1;
3.页面1重写onmessage消息事件,获取返回值
注意:postMessage(p1,p2) 参数p1最早只能接受字符串,后来改成任何数据结构。可是,并非所有浏览器都实现这一变化。为了保险起见,最好使用JSON.stringify()转成字符串,然后在接收端的onmessage事件处理程序中使用JSON.parse();
页面1中有一个按钮,希望实现点击按钮打开页面2。
页面2进行一系列操作后,点击该页面确定按钮后关闭页面,同时返回值到页面1
ps:页面1与页面2位于不同服务器,即跨域
二、实现
使用postMessage()实现上述功能。
1.页面1上的代码:
//选择表单按钮的点击事件 selectFillForm : function(){ var self = this; $("#selectForm").off('click'); $("#selectForm").on('click',function(){ window.open(url);//页面2的地址 }); }
//重写message事件以接受打开表单页面2返回的值 window.onmessage = function (e) { var student = e.data; if (student != undefined && student != null) { if(student.id != undefined && student.id != null) { var id = student.id; var name = student.name; ......//后续具体操作代码 } } };
2.页面2上返回值代码
function onOk() { var student= {name:"lily",id:1} if (window.opener) { window.opener.postMessage(student, '*'); } window.close(); }
归纳实现操作就是:
1.页面1使用window.open(url)函数打开页面2
2.页面2使用window.opener.postMessage(param1,param2)返回消息到页面1;
3.页面1重写onmessage消息事件,获取返回值
注意:postMessage(p1,p2) 参数p1最早只能接受字符串,后来改成任何数据结构。可是,并非所有浏览器都实现这一变化。为了保险起见,最好使用JSON.stringify()转成字符串,然后在接收端的onmessage事件处理程序中使用JSON.parse();
相关文章推荐
- js操作的跨域问题:js实现自动设置框架载入页面高度的问题
- JavaScript实现内嵌的iframe跨域调用父页面js方法
- js点击返回跳转到指定页面实现过程
- JS/jquery实现鼠标控制页面元素显隐
- js实现页面重定向
- 利用字节流将生成的图片输出到js页面,实现动态生成图片
- Vue.js 通过jQuery ajax获取数据实现更新后重新渲染页面
- 原生JS实现Ajax跨域请求flask响应内容
- 使用js实现滑动页面效果,很漂亮
- js实现页面跳转的几种方式
- js实现父页面的刷新
- JS实现返回上一页面并刷新
- JS实现页面的拖动布局
- 用js来刷新当前页面保留参数的具体实现
- JS跨域及Ajax实现
- 用js实现在加载完成一个页面后自动执行一个方法
- 页面定时跳转的js和php的代码实现和页面定时刷新
- js或jquery实现页面打印可局部打印
- js实现页面定时刷新功能
- Ajax跨域的解决办法:载入javascript(js)文件实现无刷新更新数据(转载)