一、使用场景
当我们需要跨域进行登录时,为了避免登录信息暴露在链接中,此时必须采用Post提交。同时Ajax是不支持跨域的。此时就可以采用在Jsp中模拟Post提交。
二、代码实现
以下实例是跨域登录后台系统,我这边登录参数比较多,大家不必纠结参数含义。替换为自己的参数就好。总体思路就是:(1)创建临时表单。(2)、设置form表单属性。(3)、form表单添加到body中。(4)、登录参数添加到form表单中。(5)、form表单提交。
/**
* 登录后台
* 功能: JS跳转页面,并已POST方式提交数据
* 参数: URL 跳转地址 PARAMTERS 参数
*/
function scanQrCodeLoginManage(busSysCode, wsSessionId, userId, name, department, mobile, headImgUrl, fansId, mpId, openId, unionId) {
console.log("scanQrCodeLoginManage");
var paramters = new Array();
paramters.push({name: "busSysCode", value: busSysCode});
paramters.push({name: "userId", value: userId});
paramters.push({name: "name", value: name});
paramters.push({name: "department", value: department});
paramters.push({name: "mobile", value: mobile});
paramters.push({name: "headImgUrl", value: headImgUrl});
paramters.push({name: "fansId", value: fansId});
paramters.push({name: "mpId", value: mpId});
paramters.push({name: "openId", value: openId});
paramters.push({name: "unionId", value: unionId});
console.log("即将登录后台,登录地址为:scanQrCodeLoginManageUrl====" + scanQrCodeLoginManageUrl);
Post(scanQrCodeLoginManageUrl, paramters);
console.log("登录完成");
return false;
}
/*
*功能: 模拟form表单的提交
*参数: URL 跳转地址 PARAMTERS 参数
*返回值:
*创建时间:20160713
*创建人:
*/
function Post(URL, PARAMTERS) {
//创建form表单
var temp_form = document.createElement("form");
temp_form.action = URL;
//如需打开新窗口,form的target属性要设置为'_blank'
temp_form.target = "_self";
temp_form.method = "post";
temp_form.style.display = "none";
//添加参数
for (var item in PARAMTERS) {
var opt = document.createElement("textarea");
opt.name = PARAMTERS[item].name;
opt.value = PARAMTERS[item].value;
temp_form.appendChild(opt);
}
document.body.appendChild(temp_form);
//提交数据
temp_form.submit();
}