当Ajax调用成功时,用户将被重定向到主页:
$('#button_1').on('click', function () {
//code
$.ajax({
method: "POST",
url: "/somewhere",
data: {
//code
}
}).done(function () {
location.href = "/";
});
});
重定向后,我想自动点击另一个按钮,打开一个模态。我在done
函数内部尝试了不同的方法:
.done(function () {
location.href = "/";
$('#button_2').click(); // doesn't work
});
.done(function () {
location.href = "/";
setTimeout(function ()
$('#button_2').click(); // doesn't execute
}, 2000);
});
.done(function () {
location.href = "/";
$(document).ready( function () {
// executes but user is immediately redirected to main page
$('#button_2').click();
});
});
我也尝试在Ajax调用所在的函数中使用Ajax,但结果相同。
如何在Ajax调用后以编程方式单击按钮?
答案 0 :(得分:5)
您需要在目标(主)页面中添加该逻辑。
重定向后,当前页面不再是活动页面,并且所有逻辑都将被删除。
您可以在URL中添加一些参数,以便了解您何时因重定向而在那里,例如:
location.href="/?redirect=1"
然后检查该参数
答案 1 :(得分:2)
旁边的代码行
location.href = "/";
将不会被执行,因为浏览器正在导航到另一个页面。
因此,您应该将您的逻辑放在/
页面中(#button_2
应该在该页面中)。
答案 2 :(得分:2)
您目前正在尝试执行直接重定向后执行代码,因为永远无法访问location.href = "/"
之后的代码。重定向后,您将拥有一个清晰状态的新页面。
您当前的功能仍然如下所示:
$('#button_1').on('click', function () {
$.ajax({
method: "POST",
url: "/somewhere",
data: {
//code
}
}).done(function () {
location.href = "/?modal-open=1";
});
});
正如您所看到的,我已经向重定向添加了一个查询参数,因此我们知道我们被重定向以打开模式。
对于您的根页(/
),您需要一个这样的脚本:
$(document).ready( function () {
// check the URL for the modal-open parameter we've just added.
if(location.search.indexOf('modal-open=1')>=0) {
$('#button_2').click();
}
});
这将检查参数是否在URL中并触发点击。
答案 3 :(得分:1)
首先,当您重定向新页面时,您无法访问DOM,因为页面已重新加载。您可以发送参数来执行此操作。
$(document).ready( function () {
//after page load
var isButtonActive = findGetParameter("isButtonActive");
if(isButtonActive){
alert("button_2 activated");
$('#button_2').click();
}
$('#button_1').on('click', function () {
//code
$.ajax({
method: "POST",
url: "/somewhere",
data: {
//code
}
}).done(function () {
alert("page will be reload. button_2 wil be activated");
location.href = "/?isButtonActive=true";
});
});
$('#button_2').on('click', function () {
alert("button_2 clicked");
});
});
function findGetParameter(parameterName) {
var result = null,
tmp = [];
location.search
.substr(1)
.split("&")
.forEach(function (item) {
tmp = item.split("=");
if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
});
return result;
}
答案 4 :(得分:1)
感谢您的回答。我研究了一下,发现了另一种方法:
$('#button_1').on('click', function () {
sessionStorage.setItem("reload", "true");
//code
$.ajax({
method: "POST",
url: "/somewhere",
data: {
//code
}
}).done(function () {
location.reload();
});
});
在主页:
$(document).ready(function () {
var reload = sessionStorage.getItem("reload");
if (reload == "true") {
$("#button_2").click();
sessionStorage.setItem("reload", false);
}
});