I am making a webpage in which I have a anchor tag '' having a URL in href but the problem is that on clicking on this anchor tag it will check the condition through ajax and by the response from the ajax it will decide whether to send to another page or not.
I have tried this so far the ajax is working good but when I click on the anchor tag the new page is open in new window and ajax run on the same and it doesn't matter whether the response is true or false
<a href="www.recordlist.com" class = "checkrecord" check_us_type = "user" target = "_blank"> check</a>
<script>
$(".checkrecord").click(function(e){
e.preventDefault();
var user_type = $(this).attr("check_us_type");
$.ajax({
type: "POST",
data: { 'ven_type' : ven_type },
url: baseUrl+"/CheckUser",
success: function(result){
if(result == "-1")
{
alert("Please login to view Details");
}else
{return true;// here it should work but it doesn't
}
},
});
});
</script>
答案 0 :(得分:0)
当您阻止了此类标签的默认行为时,您必须手动重定向它
<script>
$(".checkrecord").click(function(e) {
e.preventDefault();
var ele = e.target;
var user_type = $(this).attr("check_us_type");
$.ajax({
type: "POST",
data: {
'ven_type': ven_type
},
url: baseUrl + "/CheckUser",
success: function(result) {
if (result == "-1") {
alert("Please login to view Details");
} else {
window.location.href = $(ele).attr("href");
}
},
});
});
</script>
答案 1 :(得分:0)
e.preventDefault();
应该阻止新窗口打开。它加载了吗?您是否已准备好在文档上运行代码?如果仅在JS负载下运行代码,则可能会遇到竞争条件,并且代码执行时HTML元素尚不存在。
$( document).ready(function() {
$(".checkrecord").click(function(e){
e.preventDefault();
var user_type = $(this).attr("check_us_type");
$.ajax({
type: "POST",
data: { 'ven_type' : ven_type },
url: baseUrl + "/CheckUser",
success: function(result){
if(result == "-1")
{
alert("Not logged in!");
}else
{
alert("Logged in!");
}
},
error: function(result){
alert("error!");
},
});
});
});
我还添加了第二个回调(错误),这是处理结果的一种更好的方法。让CheckUser脚本返回HTTP代码200(表示正常)和403(拒绝/禁止)。休息就是这样,jQuery可以理解,无需自定义检查。