我遇到了jquery加载函数的问题

时间:2016-02-01 22:59:19

标签: javascript php jquery ajax

我有一个购物车,可以通过ajax调整或删除数量或购物车项目,因此页面不必刷新以反映更改等。

我有一个外部shopping_cart.js处理所有购物车js方面的东西。当我调整购物车项目数量时,我在ajax成功函数上使用DOM innerHTML来反映对用户的更改,但是为了完全删除购物车项目,我使用jquery加载函数将update_cart.php文件加载到容器div元素中,该元素显示当用户点击删除/添加/减去购物车项目时,用鼠标快速链接更新购物车内容。

由于我正在使用jquery.load来加载cart_update.php脚本,我必须在cart_update.php脚本中包含外部shopping_cart.js,以便在加载脚本时所有JS都能正常工作,但问题是我当我在cart_update.php中包含js文件并使用jquery加载它时,当我单击每个产品的任何添加/减去/删除按钮并将每个循环复合时,它似乎多次循环遍历javascript每次点击。

例如,当我第一次点击添加数量时,购物车数量将添加一个额外的项目,当我再次点击时,它将循环2个额外的项目,然后4,8,16等等。但是,如果我将外部js文件放在主php页面文件而不是cart_update脚本中,它会在页面刷新后正常工作并且不会循环,但显然javascript在购物车时不起作用当我尝试删除购物车项目时因为它无法访问js文件而加载了jquery.load,因为它未包含在cart_update.php中

我真的不确定我在哪里出错了。我只是一个新手程序员

cart_update.php

<!-- Display cart contents -->

<script src="js/shopping_cart.js"></script>

<?php 
// Call session start when the script is loaded via jquery.load
if (isset($_SESSION)){
} else {
    session_start();
}

require_once "config.php";
$session_id = session_id();

$sql = "SELECT * FROM shopping_cart WHERE session_id='$session_id'";

$stmt = $PDOconnection->prepare($sql);
$stmt->execute();

$rowCount = $stmt->rowCount();

if($rowCount < 1 ){
    echo "Your cart is empty.";
} else {

    $points = 0;

    while($result = $stmt->fetch(PDO::FETCH_ASSOC)){
        $ui          = $result['ui'];
        $item_points = $result['item_points'];

        // Display cart item name, price, quantity and amount of points earned
        echo "<br>" . $result['item_name'] . " $" . number_format($result['item_price'],2) . " Qty: " . $result['item_quantity'] . " <a href='#' class='remove_item' data-ui='$ui'> X </a><br>";  

        $points = $points + number_format($item_points, 1);
    }

    echo "<hr />";

    if (isset($_SESSION['user_name'])){
        echo "You have earned $points points with this purchase!";
    } else {
        echo "Sign up to recieve $points points with this purchase! <a href'#'>What's this?</a>";
    }

    echo "<hr />";

    echo "<a href='cart.php'>Check Out</a>";
}
?>

shopping_cart.js

function cart_data(cartData) {

    // Get data values
    var $item_stock_type  = cartData.getAttribute('data-stock-type');
    var $item_ui          = cartData.getAttribute('data-stock-ui');

    // Set value as one. As it's signle qty when adding to cart from the product list   
    var $item_qty = 1;

    $(document).ready(function(e){

        // Send data for processing in shopping_cart.php
        $.ajax({
            url: "php/shopping_cart.php",
            data: { item_stock_type: $item_stock_type, item_ui: $item_ui, item_qty: $item_qty },
            dataType: "json",
            type: "post",
            success: function(data, response){

                document.getElementById("cart_total").innerHTML = data.cart_total;
                document.getElementById("shoppingcart_link_quantity").innerHTML = data.cart_qty + '<br />';

                switch (data.success)
                {
                case 0:
                    modal({
                        type: 'error',
                        title: 'Ooops',
                        text: data.error_message,
                        center: true,
                        animate: true,                  
                    });
                    break;

                case 1:
                    modal({
                        type: 'alert',
                        title: '',
                        text: data.user_message,
                        center: true,
                        animate: true,
                        autoclose: true,
                    });  
                    break;

                case 2:
                    modal({
                        type: 'alert',
                        title: '',
                        text: data.user_message,
                        center: true,
                        animate: true,
                    });   
                    break;
                }
                // Update Shopping cart contents
                $("#shopping_cart_container").load("php/update_cart.php");              
            },
            error: function(jqXHR, status, error){

                var $jxr = jqXHR;
                var $status = status;
                var $error = error;

                // Display error message to user
                modal({
                 type: 'error',
                 title: 'Ooops!',
                 text: 'An Error has occured: <br><br>' + jqXHR + ": " + status + "; " + error,
                 center: true,
                 animate: true,
                });

                // Log error message
            }
        });
    });
}

// Remove item from shopping cart quick link 
$(document).ready( function(){

    // Remove item from cart
    $(".remove_item").click( function(e){
        e.preventDefault();

        var $ui = $(this).attr("data-ui");

        $.ajax({
            url: 'php/ajax.php',
            data: { remove_cart_item: $ui },
            dataType: "json",
            type: "post",
            success: function(data, response){

                document.getElementById("cart_total").innerHTML = data.cart_total;
                document.getElementById("shoppingcart_link_quantity").innerHTML = data.cart_qty + '<br />';

                switch (data.success)
                {
                case 0:
                    modal({
                        type: 'error',
                        title: 'Ooops',
                        text: data.error_message,
                        center: true,
                        animate: true,              
                    });
                }
                // Update Shopping cart quick link contents
                $("#shopping_cart_container").load("php/update_cart.php");              
            },
            error: function(jqXHR, status, error){

                var $jxr = jqXHR;
                var $status = status;
                var $error = error;

                // Display error message to user
                modal({
                 type: 'error',
                 title: 'Ooops!',
                 text: 'An Error has occured: <br><br>' + jqXHR + ": " + status + "; " + error,
                 center: true,
                 animate: true,
                });

                // Log error message
            }
        });
    });
});

// Add qty to shopping cart main page 
$(document).ready( function(){

    $(".add_item").click( function(e){
        e.preventDefault();

        var $ui = $(this).attr("data-ui");

        $.ajax({
            url: 'php/ajax.php',
            data: { add_cart_item: $ui },
            dataType: "json",
            type: "post",
            success: function(data, response){

                switch (data.success)
                {

                case 0:

                    // No more stock. Notify user
                    modal({
                        type: 'error',
                        title: 'Sorry',
                        text: data.error_message,
                        center: true,
                        animate: true,

                    });
                break;

                case 1:

                    // Update item qty
                    var $id = data.element_id;
                    document.getElementById("cart_total").innerHTML = data.cart_total;
                    document.getElementById("shoppingcart_link_quantity").innerHTML = data.cart_qty + '<br />';
                    document.getElementById($id).innerHTML = data.item_qty;

                    // Update Shopping cart quick link contents
                    $("#shopping_cart_container").load("php/update_cart.php");

                break;

                }           
            },
            error: function(jqXHR, status, error){

                var $jxr = jqXHR;
                var $status = status;
                var $error = error;

                // Display error message to user
                modal({
                 type: 'error',
                 title: 'Ooops!',
                 text: 'An Error has occured: <br><br>' + jqXHR + ": " + status + "; " + error,
                 center: true,
                 animate: true,
                });

                // Log error message
            }
        });
    });
});

// Minus qty to shopping cart main page 
$(document).ready( function(){

    $(".minus_item").click( function(e){
        e.preventDefault();

        var $ui = $(this).attr("data-ui");

        $.ajax({
            url: 'php/ajax.php',
            data: { minus_cart_item: $ui },
            dataType: "json",
            type: "post",
            success: function(data, response){


                switch (data.success)
                {

                case 0:
                break;

                case 1:

                    // Update item qty
                    var $id = data.element_id;
                    document.getElementById("cart_total").innerHTML = data.cart_total;
                    document.getElementById("shoppingcart_link_quantity").innerHTML = data.cart_qty + '<br />';
                    document.getElementById($id).innerHTML = data.item_qty;

                    // Update Shopping cart quick link contents
                    $("#shopping_cart_container").load("php/update_cart.php");

                break;
                }           
            },
            error: function(jqXHR, status, error){

                var $jxr = jqXHR;
                var $status = status;
                var $error = error;

                // Display error message to user
                modal({
                 type: 'error',
                 title: 'Ooops!',
                 text: 'An Error has occured: <br><br>' + jqXHR + ": " + status + "; " + error,
                 center: true,
                 animate: true,
                });

                // Log error message
            }
        });
    });
});

3 个答案:

答案 0 :(得分:1)

您正在将事件侦听器附加到使用load覆盖它们时删除的dom元素。

要修复,请使用事件委派附加到不会被删除的父元素。

例如,替换:

 $(".remove_item").click( function(e){...

使用:

 $("#shopping_cart_container").on('click','.remove_item', function(e){...

更多信息:http://api.jquery.com/on/

答案 1 :(得分:1)

  1. 只需将您的javascript添加到页面一次,不要将其与每个ajax响应一起发送。这样,您就不会在添加按钮上附加多个事件处理程序。

  2. 在脚本中更改将删除项处理程序添加到$(document).on ("click", ".minus_item", function(e){...})的方式,否则每次从ajax响应中替换basket内容时都会丢失事件处理程序。

答案 2 :(得分:0)

每次定义cart_data函数时,最终会在相同元素上生成多个事件。对此的一个解决方案是简单地重新分配它。如果它存在。

所以不是这个

function cart_data(cartData) {
     ...
}

你可以这样做

var cart_data = cart_data || function(cartData) {
    ...
}