Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
AJAX购物车-在Javascript/jQuery中实现的最佳方式_Javascript_Jquery_Ajax - Fatal编程技术网

AJAX购物车-在Javascript/jQuery中实现的最佳方式

AJAX购物车-在Javascript/jQuery中实现的最佳方式,javascript,jquery,ajax,Javascript,Jquery,Ajax,我在一个PHP电子商务网站上工作,该网站将用户购物车存储在一个会话变量中。我希望能够使用jQuery通过AJAX处理这个问题,但我不确定最好的方法 我认为我本质上想为购物车创建一个API,然后在整个系统中使用它。例如,我希望能够做到以下几点: Cart.addItem(product_id, qty); Cart.removeItem(product_id); Cart.getTotal(); 在幕后,这将向服务器发出各种AJAX请求,并根据需要更新会话: var Cart = { a

我在一个PHP电子商务网站上工作,该网站将用户购物车存储在一个会话变量中。我希望能够使用jQuery通过AJAX处理这个问题,但我不确定最好的方法

我认为我本质上想为购物车创建一个API,然后在整个系统中使用它。例如,我希望能够做到以下几点:

Cart.addItem(product_id, qty);
Cart.removeItem(product_id);
Cart.getTotal();
在幕后,这将向服务器发出各种AJAX请求,并根据需要更新会话:

var Cart = {
    addItem: function(product_id, qty){
          $.ajax({
            type: 'POST',
            data: { product_id: product_id, qty: qty },
            url: 'cartAjax.php?action=add_to_cart',                
            success: function(){
               return true;
            }
        });
    },
    removeItem: function(product_id){
          $.ajax({
            type: 'POST',
            data: { product_id: product_id },
            url: 'cartAjax.php?action=remove_from_cart',                
            success: function(){
               return true;
            }
        });
    },
    getTotal: function(){
          $.ajax({
            type: 'POST',                
            url: 'cartAjax.php?action=fetch_cart_total',                
            success: function(response){
               return response.total;
            }
         });
    }
}

这是正确的方法吗?我是否已经接近应该如何做了?

您的回复状态有点粗心,如果我是您,我会这样做:

var cartUpdatedInfo; // IMPORTANT
var Cart = {
    addItem: function(product_id, qty){
          $.ajax({
            type: 'POST',
            data: { product_id: product_id, qty: qty },
            dataType : 'json',
            url: 'cartAjax.php?action=add_to_cart',                
            success: function(data){
               if(data.result == 'DONE')
               {
                   cartUpdatedInfo = data.cartUpdatedInfo; // receives fresh data from server
               }
            }

           error : function(){
              // handle the error. VERY VERY IMPORTANT, to avoid scrip-level
              // errors to be exposed to the user
           }
        });
    },
 // the rest of the code
在PHP中,完成操作后,我会返回以下内容:

/// operation done
if($operationDoneSuccessfully)
{
   // though you probably want to use echo
   return json_encode(array('result'=>'DONE', 'cartUpdatedInfo' => $cartInfo)); 
}
使用上述方法,您可以使用服务器发送的新的有效数据更新购物车信息(或验证客户端对的更改)

此外,值得将用户限制为一次单击/请求,这意味着您最好为addToCart按钮的单击事件设置禁用功能,这意味着:

$("#addToCart").on("click", function(){
     // after doing certain things for prpation
     var cartBtn = $(this);
     setTimeout(function(){
         cartBtn.prop("disabled", true);
     }, 200);
});
您可以稍后在ajax完成后重新启用它

关于检查请求并发性和/或其有效性的另一点,您可以在AJAX名称中添加另一个参数,如“token”或“_token”或您喜欢的任何内容:

$.ajax({
   data : { token : randId(25) /* ..... */ },
   // the rest
});
randId()函数可以是这样的:

function randId(len)
{
  var newNum = "";
  for(i = 0; i < len; i++)
  {
     newNum += getRandomInt(0,9);
  }
  return newNum;
}
函数randId(len)
{
var newNum=“”;
对于(i=0;i
您可以在生成的随机性的开头添加任意值,这允许您确保这是您自己的随机生成标记:

function randId(len)
{
  var newNum = "";
  for(i = 0; i < len; i++)
  {
     newNum += getRandomInt(0,9);
  }
  return "token"+newNum;
}

// Returns a random integer between min (included) and max (excluded)
// Using Math.round() will give you a non-uniform distribution!
function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
} // Copied from MDN Javascript Documentation
函数randId(len)
{
var newNum=“”;
对于(i=0;i
我将数字视为字符串,以避免为大整数分配内存

另外,请注意,要在服务器端增强AJAX,需要做以下几件事:

  • 将会话设置为限制用户对同一URL的并发请求 用户

  • 每次检查每个任务的用户id或会话

  • < P>始终把用户看作是做某事的人 更改AJAX发送的输入


很高兴看到它的帮助