Ajax不止一次地打电话

时间:2016-01-26 14:26:01

标签: javascript php jquery ajax

我的ajax代码有一个问题。它不止一次被召唤。我的PHP代码是下一个:

while循环,我从数据库中获取所有结果。我只粘贴了一个模态和一个下拉菜单,因为其他一切正常

$rezPet = mysqli_query($kon, "SELECT * FROM pets WHERE user_id = ". $userId ." ORDER BY id DESC");
while($redPet = mysqli_fetch_assoc($rezPet)){


......
<div id=\"confirmBox-". $redPet["id"] ."\" class=\"modal fade bs-example-modal-xs\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"mySmallModalLabel\">
    <div class=\"modal-dialog modal-sm\">
      <div class=\"modal-content\">
            <div class=\"modal-header\">
                <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;</span></button>
                <h4 class=\"modal-title\" id=\"myModalLabel\"><b>". $redPet["name"] ."</b> is gevonden?</h4>
            </div>
            <div class=\"modal-body\">
                Bent u zeker dat <b>". $redPet["name"] ."</b> gevonden is?
            </div>
            <div class=\"modal-footer\">
                <button id=\"btnFoundCancel-". $redPet["id"] ."\" type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\"><i class=\"fa fa-ban\"></i>  Cancel</button>
                <button id=\"btnFoundConfirm-". $redPet["id"] ."\" type=\"button\" class=\"btn btn-primary\" data-dismiss=\"modal\"><i class=\"fa fa-floppy-o\"></i>  Ja! Ga verder</button>
            </div>
     </div>
    </div>
</div>

.
.
.
<div id=\"dropdown-". $redPet["id"] ."\" class=\"col-md-6 col-xs-12\" style=\"padding-right:10px;z-index:99999999;". $showHideDropdown ."\">
        <!-- Split button -->
        <div class=\"btn-group pull-right\">
        <button type=\"button\" id=\"dataTitle\" data-title=\"Beheer informatie over uw dier\" class=\"btn btn-success btn-xs\"><i class=\"fa fa-pencil-square-o\"></i></button>
        <button type=\"button\" id=\"dataTitle\" data-title=\"Beheer informatie over uw dier\" class=\"btn btn-success btn-xs dropdown-toggle\" data-toggle=\"dropdown\" aria-haspopup=\"true\" aria-expanded=\"false\">
        <span class=\"caret\" style=\"margin-top:0;\"></span>
        <span class=\"sr-only\">Toggle Dropdown</span>
        </button>
        <ul id=\"drpDown-". $redPet["id"] ."\" class=\"dropdown-menu\">
                <li class=\"col-lg-12\">
                    <button id=\"dataTitle btnFound-". $redPet["id"] ."\" class=\"btnFound btn btn-success col-lg-12 col-sm-12 col-md-12 col-xs-12 btn-sm\" data-title=\"Klik hier als uw dier gevonden is\" data-target=\"#confirmBox-". $redPet["id"] ."\" data-toggle=\"modal\"><i class=\"fa fa-home\"></i>  Gevonden</button>
                </li>
                <div style=\"clear:both;\"></div><li role=\"separator\" class=\"divide5\"></li>
                <li class=\"col-lg-12\">
                    <form action=\"dier-toevoegen.php\" method=\"POST\">
                        <input type=\"hidden\" name=\"changeID\" value=\"". $redPet["id"] ."\">
                        <button id=\"dataTitle\" class=\"btn btn-info col-lg-12 col-sm-12 col-md-12 col-xs-12 btn-sm\" data-title=\"Klik hier om de informatie over uw dier te wijzigen\" type=\"submit\"><i class=\"fa fa-pencil\"></i>  Wijzigen</button>
                    </form>
                </li>
                <div style=\"clear:both;\"></div>
                <li role=\"separator\" class=\"divider\"></li>
                <li class=\"col-lg-12\">
                    <button id=\"dataTitle btnVerwijderen-". $redPet["id"] ."\" class=\"linkDelete btn btn-danger col-lg-12 col-sm-12 col-md-12 col-xs-12 btn-sm\" data-title=\"Klik hier om uw dier te verwijderen\" href=\"#\"><i class=\"fa fa-trash\"></i>  Verwijderen</button>
                </li>
            </ul>
        </div>
    </div>

}

我的ajax代码是下一个:

第一个ajax代码,我将数据库字段更新为值1,它工作正常,唯一的问题是因为它已经被调用了一次

<script type="text/javascript">
    $(document).ready(function() {
        $(document).on("click","button[class*=btnFound]", function(e){
            var cijeliID = this.id.split("-");
            var id = cijeliID[1];
            $($("#confirmBox-"+id).data("target")).fadeIn(400);

            $(document).on("click", "#btnFoundConfirm-"+id, function(){
                /*$("#confirmBox-"+id).modal('toggle');*/
                $.ajax({
                    url : "pet-found.php",
                    type: "POST",
                    dataType: "json",
                    data : {id : id, status:"found", sessionCode : "<?php echo $session_code; ?>"},
                    beforeSend: function(){
                        $("#info-middle-register").show();
                    },

                    success: function(msg){
                        $("#info-middle-register").hide();
                        if(msg.result == "Found"){
                            $("#delpetsuccess-"+id).html("<i class=\"fa fa-thumbs-o-up\"></i>  Uw huisdier is thuis. De VermisteDieren site wenst u veel plezier met uw beestje.").fadeIn(300).fadeOut(10000);
                            $("#watermark-"+id).show();
                            $("#drpDown-"+id).html("<li id=\"liTochGezocht-"+id+"\" class=\"col-lg-12\"><button id=\"dataTitle btnNotFound-"+id+"\" class=\"btnNotFound btn btn-primary col-lg-12 xol-sm-12 col-md-12 col-xs-12 btn-sm\" data-title=\"Klik hier als uw beestje toch nog niet gevonden is.\"><i class=\"fa fa-arrow-left\"></i>  Toch nog gezocht?</button></li>");
                            $("#dier-"+id).addClass("opacityClass");

                        }else{
                            if(msg.result == "NotFound"){
                                $("#delpeterror-"+id).html("<i class=\"fa fa-exclamation-triangle\"></i>  Er is iets misgelopen. Contacteer ons via info@vermistedieren.be.").fadeIn(300).fadeOut(10000);
                            }
                        }
                    },

                    error: function(){
                        $("#info-middle-register").hide();
                        $("#delpeterror-"+id).html("<i class=\"fa fa-exclamation-triangle\"></i>  Er is iets misgelopen. Contacteer ons via info@vermistedieren.be.").fadeIn(300).fadeOut(10000);
                    }
                })
            });
            e.preventDefault();
        });
    });
</script>

(第二个代码,我将数据库字段更新为值0)

<!-- Ako klikne na go back kada je zivotinja oznacena kao pronadjena -->
<script type="text/javascript">
    $(document).ready(function() {
        $(document).on("click","button[class*=btnNotFound]", function(e){
            var cijeliID = this.id.split("-");
            var id = cijeliID[1];

            $.ajax({
                url : "pet-found.php",
                type: "POST",
                dataType: "json",
                data : {id : id, status:"notFound", sessionCode : "<?php echo $session_code; ?>"},
                beforeSend: function(){
                    $("#info-middle-register").show();
                },

                success: function(msg){
                    $("#info-middle-register").hide();
                    if(msg.result == "changeMindNotFound"){
                        $("#watermark-"+id).hide();
                        $("#dier-"+id).removeClass("opacityClass");
                        $("#txtFound-"+id).hide();
                        $("#liTochGezocht-"+id).hide();
                        $("#drpDown-"+id).html("<li class=\"col-lg-12\"><button id=\"dataTitle btnFound-"+id+"\" class=\"btnFound btn btn-success col-lg-12 col-sm-12 col-md-12 col-xs-12 btn-sm\" data-title=\"Klik hier als uw dier gevonden is\" data-target=\"#confirmBox-"+id+"\" data-toggle=\"modal\"><i class=\"fa fa-home\"></i>  Gevonden</button></li><div style=\"clear:both;\"></div><li role=\"separator\" class=\"divide5\"></li><li class=\"col-lg-12\"><form action=\"dier-toevoegen.php\" method=\"POST\"><input type=\"hidden\" name=\"changeID\" value=\""+id+"\"><button id=\"dataTitle\" class=\"btn btn-info col-lg-12 col-sm-12 col-md-12 col-xs-12 btn-sm\" data-title=\"Klik hier om de informatie over uw dier te wijzigen\" type=\"submit\"><i class=\"fa fa-pencil\"></i>  Wijzigen</button></form></li><div style=\"clear:both;\"></div><li role=\"separator\" class=\"divider\"></li>                                            <li class=\"col-lg-12\"><button id=\"dataTitle btnVerwijderen-"+id+"\" class=\"linkDelete btn btn-danger col-lg-12 col-sm-12 col-md-12 col-xs-12 btn-sm\" data-title=\"Klik hier om uw dier te verwijderen\" href=\"#\"><i class=\"fa fa-trash\"></i>  Verwijderen</button></li>");

                    }else{
                        if(msg.result == "changeMindFound"){
                            $("#delpeterror-"+id).html("<i class=\"fa fa-exclamation-triangle\"></i>  Er is iets misgelopen. Contacteer ons via info@vermistedieren.be.").fadeIn(300).fadeOut(10000);
                        }
                    }
                },

                error: function(){
                    $("#info-middle-register").hide();
                    $("#delpeterror-"+id).html("<i class=\"fa fa-exclamation-triangle\"></i>  Er is iets misgelopen. Contacteer ons via info@vermistedieren.be.").fadeIn(300).fadeOut(10000);
                }
            })
        });
    });
</script>

当页面第一次加载时,如果我点击&#34; Gevonden&#34;按钮,比一切都完美。第一个ajax代码被调用一次就可以了。 但是,dropmenu的列表项只改为一个按钮(&#34; toch nog gezoch&#34;)。如果我点击它,就会调用第二个ajax代码,它会执行它需要做的事情。

然后,下拉菜单中的列表项再次更改为前三个按钮(Gevonden,Wijzigen,Verwijderen)。而且我遇到了问题。当我点击gevonden按钮时,第一个ajax代码被调用两次。每次下一次尝试都是第一次被称为ajax的代码。

任何消化?提前谢谢。

3 个答案:

答案 0 :(得分:0)

试试这个:)

<script type="text/javascript">
    $(document).ready(function() {
        $(document).on("click","button[class*=btnNotFound]", function(e){

          // add this around
          if (e.handled !== true) {
            e.handled = true; // prevent firing two times

            // your code


          }

答案 1 :(得分:0)

我在我正在工作的项目上遇到了同样的问题,这就是我解决它的方法(这是项目中的实际代码示例):

$(document).ajaxComplete(function () {
    var didItRun = false; //I'm using this boolean to check if I already ran this code.
    $('#filterForm2GoodsReceived input').change(function () {
        if(didItRun == false)
        {
            $.ajax({
                type: "GET",
                url: "/Receiving/List/",
                data: $('#filterForm2GoodsReceived').serialize(),
                success: function (response) {
                    $('#listReceivingOrders').html(response);
                    return false;
                }
            })
            didItRun = true;
        }
    })
})

答案 2 :(得分:0)

我有一个解决方案。 @JamesThorpe说,我把另一个点击事件分开了。

<script type="text/javascript">
    $(document).ready(function() {
        $(document).on("click","button[class*=btnFound]", function(e){
            var cijeliID = this.id.split("-");
            var id = cijeliID[1];
            $($("#confirmBox-"+id).data("target")).fadeIn(400);
            e.preventDefault();
        });
    });
</script>
<script type="text/javascript">
$(document).ready(function() {
    $(document).on("click", ".btnFoundConfirm", function(){
        var cijeliID = this.id.split("-");
        var id = cijeliID[1];
        /*$("#confirmBox-"+id).modal('toggle');*/
        $.ajax({
            url : "pet-found.php",
            type: "POST",
            dataType: "json",
            data : {id : id, status:"found", sessionCode : "<?php echo $session_code; ?>"},
            beforeSend: function(){
                $("#info-middle-register").show();
            },

            success: function(msg){
                $("#info-middle-register").hide();
                if(msg.result == "Found"){
                    $("#delpetsuccess-"+id).html("<i class=\"fa fa-thumbs-o-up\"></i>  Uw huisdier is thuis. De VermisteDieren site wenst u veel plezier met uw beestje.").fadeIn(300).fadeOut(10000);
                    $("#watermark-"+id).show();
                    $("#drpDown-"+id).html("<li id=\"liTochGezocht-"+id+"\" class=\"col-lg-12\"><button id=\"dataTitle btnNotFound-"+id+"\" class=\"btnNotFound btn btn-primary col-lg-12 xol-sm-12 col-md-12 col-xs-12 btn-sm\" data-title=\"Klik hier als uw beestje toch nog niet gevonden is.\"><i class=\"fa fa-arrow-left\"></i>  Toch nog gezocht?</button></li>");
                    $("#dier-"+id).addClass("opacityClass");

                }else{
                    if(msg.result == "NotFound"){
                        $("#delpeterror-"+id).html("<i class=\"fa fa-exclamation-triangle\"></i>  Er is iets misgelopen. Contacteer ons via info@vermistedieren.be.").fadeIn(300).fadeOut(10000);
                    }
                }
            },

            error: function(){
                $("#info-middle-register").hide();
                $("#delpeterror-"+id).html("<i class=\"fa fa-exclamation-triangle\"></i>  Er is iets misgelopen. Contacteer ons via info@vermistedieren.be.").fadeIn(300).fadeOut(10000);
            }
        })
    });
});

</script>

在一个模态按钮(Ja!Ga verder)中,我添加了一个类btnFoundConfirm并且它有效。