前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >JS post方式打开新窗口

JS post方式打开新窗口

作者头像
郭顺发
发布2023-07-17 17:57:23
4220
发布2023-07-17 17:57:23
举报
文章被收录于专栏:pandacode_cnpandacode_cn

原理:

  1. 前端在打开浏览器窗口的同时,放入一段html代码。
  2. html代码包含表单,也就相当于模拟表单post方式提交。
  3. 后端接口也通过表单的方式接受参数。

1. html

代码语言:javascript
复制
<input id="btn_amp" type="button" value="点点点" />
<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>

<script>
    $(function () {
        $("#btn_amp").click(function () {
            var url = "http://localhost:8080/test3";
            var keys = ["userName"];
            var values = ["123"];
            openWindowWithPost(url, "预览", 500, 400, null, keys, values);
        });
    });
    /**
     * 调用
     */
    function openWindowWithPost(url, name, width, height, resizable, keys, values) {
        var screenWidth = screen.availWidth, screenHeight = screen.availHeight;
        var para = "";
        para += 'width=' + (width ? width : screenWidth - 20);
        para += ',height=' + (height ? height : screenHeight - 43);
        para += ',left=' + (width ? (screenWidth - width) / 2 : 0);
        para += ',top=' + (height ? (screenHeight - height) / 2 : 0);
        if (resizable) para += ',resizable = yes';
        if (!name) name = "";

        var newWindow = window.open("", name, para);
        if (!newWindow) {
            return false;
        }

        var html = "";
        html += "<html><head></head><body><form id='formid' method='post' action='" + url + "'>";
        if (keys && values && (keys.length == values.length)) {
            for (var i = 0; i < keys.length; i++) {
                html += "<input type='hidden' name='" + keys[i] + "' value='" + values[i] + "'/>";
            }
        }

        html += "</form><script type='text/javascript'>document.getElementById(\"formid\").submit()<\/script><\/body><\/html>";
        newWindow.document.write(html);
        return newWindow;
    }
</script>

2. 接口

代码语言:javascript
复制
@PostMapping("/test3")
public String test3Conllection(@RequestParam("userName") String userName) {
    return "测试成功!userName="+userName;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-07-01 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. html
  • 2. 接口
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档