不隐藏提交
从ajax中年获取到的key为path的参数,当他不为空就跳转到另一页面(带参数请求的形式),想隐藏的话要用表单提交的方式。
if (data.path!=null)
window.location.href = "index.jsp?path="+data.path;
另一个网页的js,使用正则获取到url该参数的值,拼接成html展示。
<script type="text/javascript">
$(function(){
let str = getQueryString("path");//获取key为path的value
display(str);
})
/**
* 拼接html页面并展示
* @param path 传递过来的图片路径
*/
function display(path) {
let html="<img src='"+path+"'>"
$("img").remove();
$("#play").append(html);
}
/**
* 正则表达式获取路径
* @param name key
* @returns {string|null} value
*/
function getQueryString(name) {
let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
let r = window.location.search.substr(1).match(reg);
if (r != null) return decodeURI(r[2]); return null;
}
</script>
<body>
<div id="play"></div>
</body>
隐藏提交
首先还是拼接成html代码输出,其中需要修改的地方就是input里面的name和path,path也就是我们要提交过去的数据。action就是要跳转的页面。
注意:其中会遇到一个问题,就是这样传过去的/号会被转义,下面会讲它的转换方法
if (data.path!=null) {
let path=data.path;
document.write("<form action='index.jsp' method='get' name='myform' style='display:none'>");
document.write("<input type='hidden' name='path' value='"+path+"'/>");
document.write("</form>");
document.myform.submit();
}
数据处理
代码几乎和之前一样,变动的地方就只有这里,return那里,我加上了替换符号,这样之后,传递过来的值都正确了,如果要传其他的除“/”符号的,可以看下下面的转换。
function getQueryString(name) {
let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
let r = window.location.search.substr(1).match(reg);
if (r != null) return decodeURI(r[2]).replace("%2F","/");return null;
}
常见的转换替换,我看的这位老哥的
表单特俗字符转换
.replace("#", "%23")
.replace("%", "%25")
.replace("&", "%26")
.replace("+", "%2B")
.replace("//", "%2F")
.replace("=", "%3D")
.replace("?", "%3F")