2013-05-07 44 views
-2

如何使用Plus,Minus按鈕更新我正在使用的自定義PHP購物車中的產品數量而不刷新頁面?使用Plus,Minus按鈕更新產品數量而不刷新頁面JavaScript

我想添加或刪除數量,無需重新加載頁面。

購物車中的商品列出如下。

 
Burger $3.99 
Pasta Bowl $8.99 

我想要一個圖像按鈕來增加或減少像下面的數量。當你點擊加號或減號時,應該顯示增加和減少的選項。

 
1 Burger $3.99 
2 Pasta Bowl $17.98 

感謝, 拉吉

+3

使用ajax來實現這個 – dee 2013-05-07 17:05:47

+0

如何?任何示例代碼? – 2013-05-07 17:06:25

+0

你有什麼基本代碼。使用jQuery和Ajax。 – Garrett 2013-05-07 17:07:23

回答

0

正如webgal建議的那樣,AJAX是前進的方向。調用一個函數的加號/減號按鈕,如updateQuantity(direction),方向是向上或向下(取決於點擊的按鈕,因此,加號按鈕將調用updateQuantity(1),減號按鈕將調用updateQuantity(-1)並使用該值來操縱對象的數量。車

簡單的Ajax代碼(你只需要定製自己的需要)將如下:

function updateQuantity(direction){ 
    var xmlhttp; 

    if(window.XMLHttpRequest){ 
     // For new browsers and IE7+ 
     xmlhttp=new XMLHttpRequest(); 
     console.log('created XMLHttpRequest'); 
    }else{ 
     // For old IE versions (volatile) 
     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
     console.log('created ActiveXObject'); 
    } 

    xmlhttp.onreadystatechange=function(){ 
     if(xmlhttp.readyState==4 && xmlhttp.status==200){ 
      //if the AJAX call is finished and the HTTP status is 200 (OK) 
      console.log('response received'); 
      var e = document.getElementById('theElementYouWantToChange'); 
      e.innerHTML = xmlhttp.responseText; 
     }else if(xmlhttp.readyState==4 && xmlhttp.status!=200){ 
     //second if condition specified, else the console will log an error 
     //whenever the readystate changes, and this happens 3 times during 
     //an acceptable AJAX call  
      console.log("Error retrieving search response. Status: "+xmlhttp.status); 
     } 
    } 

    xmlhttp.open("GET","includes/updateCart.php?product="+productID+"&change="+direction,true); 
    xmlhttp.send(); 
} 

您將需要設置變量其中的productID重視產品您正在修改數量

+0

謝謝詹姆斯。我有個好主意。 – 2013-05-07 19:25:38

0
$('#plus').click(function(){ 
    $.get('yourphpfile?val=value_to_increment', function(data){ 
    //code to update your html. 
    //data variable will hold whatever you echo from php. 
    //it's considering only simple use, you can use JSON for more complex operations. 
    }); 
}); 

基本上所有你需要做的就是創建點擊圖像(每個按鈕)事件 則值傳遞與PHP服務器/文件要從服務器更新數據以及在回調函數中,您只需使用php代碼提供的數據更新dom(您的html)。