gpt4 book ai didi

javascript - 如果 $.post() 之后有重定向,则 $.post() 不起作用 : window. location.href =

转载 作者:行者123 更新时间:2023-12-02 17:47:42 25 4
gpt4 key购买 nike

我有一个列表,当单击该列表中的一个元素时,我想在数据库中记录一些信息,因此我使用以下内容:

<li class="item"><a href="javascript:addactivity()">Add activity</a></li>

<script>
function addactivity(){

$.post('update.php');
window.location.href = "http://www.mysite.com/page.php";

}
</script>

如果我注释掉 window.location.href = "http://www.mysite.com/page.php ";数据库已更新,因为 $.post('update.php');工作正常。如果我不注释掉 window.location.href = "http://www.mysite.com/page.php ";数据库未更新,但重定向至 www.mysite.com。

出于某种原因添加 window.location.href = "http://www.mysite.com/page.php ";停止 $.post('update.php');从运行。有办法解决这个问题吗?

最佳答案

使用回调来管理情况:

function onSuccess() {
window.location.href = "http://www.mysite.com/page.php";
}

function onFailure() {
alert('An error has ocurred while updating database');
}

$.post('update.php').done(onSuccess).fail(onFailure);

读入the documentation其他示例及其工作原理:

As of jQuery 1.5, all of jQuery's Ajax methods return a superset of the XMLHTTPRequest object. This jQuery XHR object, or "jqXHR," returned by $.get() implements the Promise interface, giving it all the properties, methods, and behavior of a Promise (see Deferred object for more information). The jqXHR.done() (for success), jqXHR.fail() (for error), and jqXHR.always() (for completion, whether success or error) methods take a function argument that is called when the request terminates.

这里讨论的是 $.get,但同样适用于 $.post。

关于javascript - 如果 $.post() 之后有重定向,则 $.post() 不起作用 : window. location.href =,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21616670/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com