[英]Following link href after successful ajax call
我有一个正常的链接:
<a href="http://www.google.com" class="continue">Continue</a>
我已将点击绑定到事件以发布这样的ajax请求:
$('.continue').click(function () {
$.ajax({
type: 'POST',
url: '/url-to-post-to',
data: mydata,
contentType: 'application/json',
error: function (err) {
alert("error - " + err);
},
success: function () {
return true;
}
});
});
我想要实现的是成功后要遵循的环节......
即,如果没有错误,应将用户重定向到谷歌。
我知道我可以将window.location.href
放在成功处理程序中,但我试图尽可能避免这种情况
不幸的是(在你的情况下),ajax是异步的,这意味着你的click函数启动ajax调用然后继续运行而不注意它的作用(因此最后不返回任何内容)。
成功函数稍后调用(当ajax成功返回时)并且是一个完全不同的函数,因此它的返回true
与您的原始单击函数无关。
所有这些,你需要使用javascript来覆盖锚标签的自然行为(直接转到google.com)以及之后发生的事情(重定向)。
$('.continue').click(function (e) {
e.preventDefault(); // otherwise, it won't wait for the ajax response
$link = $(this); // because '$(this)' will be out of scope in your callback
$.ajax({
type: 'POST',
url: '/url-to-post-to',
data: mydata,
contentType: 'application/json',
error: function (err) {
alert("error - " + err);
},
success: function () {
window.location.href = $link.attr('href');
}
});
});
你尝试过这样的事情:
$('.continue').click(function(e) {
e.preventDefault();
var link = $(this).attr('href');
$.ajax({
type: 'POST',
url: '/url-to-post-to',
data: mydata,
contentType: 'application/json',
error: function (err) {
alert("error - " + err);
},
success: function () {
window.location.href = link; // <-- This line
}
});
});
或者,如果链接与响应文本一起发送,请使用该数据。
编辑:我没有看到你的最后一行,不想使用它的原因是什么? 它非常动态,并且支持所有支持JavaScript的浏览器。
你可以试试这个,
$('.continue').click(function () {
$.ajax({
type: 'POST',
url: '/url-to-post-to',
data: mydata,
contentType: 'application/json',
error: function (err) {
alert("error - " + err);
},
success: function () {
$(location).attr('href',$(this).attr('href'));
}
});
return false;
});
如果我们需要在这里实际“点击”,我们应该只是新触发click事件并允许它在第二次点击时返回true。
$('.continue').click(function ()
{
if ($(this).attr('tracked')!=undefined)
{
return true;
}
a = $(this);
$.ajax({
type: 'POST',
url: '/url-to-post-to',
data: mydata,
contentType: 'application/json',
error: function (err) {
alert("error - " + err);
},
success: function () {
$(this).attr('tracked',true);
$(a)[0].click();
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.