未调用 Ajax 函数

Ajax function not called

本文关键字:函数 Ajax 调用      更新时间:2023-09-26

嘿伙计们,我在调用 ajax 函数时遇到了问题。我尝试访问"删除.php"页面,但它从未被调用。这是我的脚本代码:

 <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
        <script>
            function deleteSpark(sparkID) {
                    var answer = confirm(sparkID);
                    //Send the user to the correct page when he presses 'yes / oke'
                    if(answer==0){
                        var ajax= $.ajax({ type: "post",
                            data: {sparkid: sparkID },
                            url: 'delete.php'
                        });
                        ajax.done(function(){
                            window.location.href = "/sparks.html";
                        });
                        ajax.fail(function(){
                            window.location.href = "/index.html";
                        })
                    }
                    /* OR*/

                    /* this method after all other code in handler*/
                // window.location.href = "/delete.php?sparkid=" + sparkID;
                // window.location.href = "/sparks.html";
                //Returns false so no events will be executed.
                return false;
            }

我用一个按钮调用它:删除 8

在我的 php 文件"delete.php"中,我这样做:$sparkID = $_POST['sparkid'];

但它永远不会被召唤,因为我试图回声并做一些其他不起作用的事情。有人可以帮助我吗?

我还没有足够的声誉来评论。 你能检查元素(Firefox/Chrome),然后在AJAX运行时查看"网络"选项卡吗? 这应该显示正在发送的数据,它被发送到哪个页面,等等......并且应该可以帮助您调试。

您可能还想尝试最初使用绝对 URL,以确保它到达正确的页面。

谢谢

安德鲁

我假设,如果返回 false 不是为了防止事件,您希望在确认不是"是"时返回 false。所以我在else语句中移动了返回 false。

现在,正如@Sergey Yarotskiy所指出的,你的if状态是真正的问题,因为你正在等待一个0;你可以像这样组合(如果你在其他地方需要变量答案),或者如果不需要这样:if(answer = confirm(sparkID)){ if(confirm(sparkID)){

希望这对您有所帮助。

这应该可以解决它:

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
        <script>
            function deleteSpark(sparkID) {
                    //Send the user to the correct page when he presses 'yes / oke'
                    if(answer = confirm(sparkID)){
                        var ajax= $.ajax({ type: "post",
                            data: {sparkid: sparkID },
                            url: 'delete.php'
                        });
                        ajax.done(function(){
                            window.location.href = "/sparks.html";
                        });
                        ajax.fail(function(){
                            window.location.href = "/index.html";
                        })
                    }else{
                     return false;
                    }
            }

'confirm' 将返回 true 或 false 而不是 0,因此请将条件更改为

if (answer) {
    // do staff
}