ajax请求响应中window.open拦截解决

来源:互联网 发布:java递归求和 编辑:程序博客网 时间:2024/06/04 18:47

问题原因:

ajax回调函数中执行window.open或者模拟click事件,由于跳转操作不是用户主动触发,会被认为不安全,浏览器会进行拦截。
1: 在fun方法中调用window.open是不会被拦截的。
2:如果不是打开新窗口,而是改原来的网页地址,可以使用window.location = newurl 来实现,这样不会被拦截。

具体解决:

function  fun(){     var tmpWin  = window.open()      ajax(xxx, handle(){             //回调函数            var  newurl  = xxxx            tmpWin.location.href = newurl;       })}

上面方法,存在一个问题时,因为先打开了空白窗口,如果ajax请求失败(网络或业务逻辑问题)后, 新窗口中就不会有正常的结果体现,有可能造成用户疑惑。
一个解决办法是,当ajax出现问题时,可以考虑给出一个提示,如 tmpWin.document.write(“服务器处理异常”);

甚至为了防止ajax响应时间过长,当窗口新建后,立即给出提示 tmpWin.document.write(“服务器正在处理中,请稍后”);

后面如果ajax正常返回,则因为设置了location值,原来打印的信息会被新的页面信息覆盖。

其他:ajax改为同步执行,用户等待时间较长,体验不好。而且服务器不能很快返回结果时仍会被拦截。

另: url参数都是字符串 需利用JSON.parse/stringify/ encodeURIComponent/decodeURIComponent进行转换
GET请求会刷新页面
POST请求模拟form表单提交

if(JumpData.method=='POST'){    postcall(JumpData.url,JumpData.parameter);     actionFun = function(){       //POST请求 param参数遍历为form表单的input进行submit       tempform.submit();     } }else if(JumpData.method=='GET'){     //GET请求请求参数在url内     actionFun = function(){         window.location.replace(JumpData.url)     } } function postcall(url,params){   tempform = document.createElement("form");    tempform.action = url;    tempform.method = "post";    tempform.style.display="none";    for (var x in params) {        var opt = document.createElement("input");        opt.name = x;        opt.setAttribute("value",params[x]);        tempform.appendChild(opt);    }    var opt = document.createElement("input");    opt.type = "submit";    opt.name = "postsubmit";    tempform.appendChild(opt);    document.body.appendChild(tempform);}setTimeout(function(){   actionFun && actionFun();},JumpData.second);
0 0
原创粉丝点击