window.open实现post方式复杂参数传递

一、需求分析

最近在项目中,有个导出word的需求,但是需要传递一些复杂的参数到后端进行数据查询后再进行导出,需要使用window.open()方法实现。如果是简单参数并且参数不重要的话,可以使用get方式直接在url上进行参数拼接,然后后台直接获取即可。但是目前我需要传递的参数有好几个,并且还有一些是序列化后的json等等,有可能会超长。这个时候如果是使用get方式的话,就可能会存在一些问题。因为get方式请求有长度限制,并且url中如果包含非法字符的话,会报错。

由此,我改为了使用post放在在window.open打开新窗口的时候,将所有参数都传递到后端服务。

GET方式:直接在url上面进行拼接

window.open(window.baseUrl + "/xxxx?name=" + name + "&age=" + age

二、实现方式

一般网页的post都是通过form来实现的,所以这里以模拟form表单提交,创建一些隐藏域存放需要传递的参数,然后手动触发formonSubmit监听事件,将formtarget设置成和openname参数一样的值,通过浏览器自动识别实现了将内容post到新窗口中。

具体代码如下:(笔者使用的是react)

//导出
exportPreviewEvaluationForm = () => {
    //....省略一些代码
    const {currentHjId, currentXsid, currentTaskId, currentLcid, currentXsxm} = this.props;
    this.downloadWord(window.baseUrl + "/xxxxxxx", currentTaskId, currentXsid, currentHjId, currentLcid, currentXsxm, previewFormDetail, cpxIdArr.toString(), "_blank")
};

//创建隐藏表单Input域
createHideInput = (name, value) => {
    let hideInput = document.createElement("input");
    hideInput.type = "hidden";
    hideInput.name = name;
    hideInput.value = value;
    return hideInput;
};

downloadWord = (url, rwid, xsid, hjid, lcid, xm, cpxqxx, cpxIdArr, name) => {
    let hideSubmitForm = document.createElement("form");
    hideSubmitForm.id = "tempForm1";
    hideSubmitForm.method = "post";
    hideSubmitForm.action = url;
    hideSubmitForm.target = name;
    hideSubmitForm.appendChild(this.createHideInput("rwid", rwid));
    hideSubmitForm.appendChild(this.createHideInput("hjid", hjid));
    hideSubmitForm.appendChild(this.createHideInput("lcid", lcid));
    hideSubmitForm.appendChild(this.createHideInput("xsid", xsid));
    hideSubmitForm.appendChild(this.createHideInput("xm", xm));
    hideSubmitForm.appendChild(this.createHideInput("cpxqxx", cpxqxx));
    hideSubmitForm.appendChild(this.createHideInput("cpxids", cpxIdArr));
    hideSubmitForm.addEventListener('onsubmit', () => {
        this.openDownloadWindow(name);
    });
    document.body.appendChild(hideSubmitForm);
    hideSubmitForm.submit();
    document.body.removeChild(hideSubmitForm);
};

openDownloadWindow = (name) => {
    window.open('about:blank', name, 'height=400, width=400, top=0, left=0, toolbar=yes, menubar=yes, scrollbars=yes, resizable=yes,location=yes, status=yes');
};

后端接收:

// 1. 获取导出需要的一些参数
String xsid = request.getParameter("xsid");
String rwid = request.getParameter("rwid");
String hjid = request.getParameter("hjid");
String lcid = request.getParameter("lcid");
String cpxqxx = request.getParameter("cpxqxx");
String xm = request.getParameter("xm");
String cpxIds = request.getParameter("cpxids");

这样就实现了post方式传递复杂参数。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值