JS + Cookie shopping cart

Source: Internet
Author: User
Tags set cookie

I am writing a mall system recently. I plan to open a clothing store by myself.

Everyone knows that shopping carts are inseparable from the shopping mall system. It is observed that shopping carts of most online shopping mall programs use a simple storage method to implement shopping carts, that is to directly splice the selected ID. Of course, this approach is sufficient when the demand is not high, but it is not sufficient to have a more robust shopping cart.

My method is to store the basic attributes of items in the shopping cart, such as the product name, quantity, current price, and image address.

How can we store these attributes?
The method is not unique. Databases, sessions, cookies ......, Most of my friends may choose databases. I chose cookies because the shopping cart is only used to provide a convenient centralized container for users to buy products. Since it is for temporary use, why bother with the database? The principle of writing a program is to decompress the server as much as possible. Cookies are stored on the client.
 


We chose cookies for storage, So how should we operate on this "cookies.
How to operate cookies and implement shopping cart?
In other words, try to decompress the server as much as possible. Since the client's stuff is used for storage, we can also use the client's stuff for operations, that is, JavaScript. Well, JS can directly read and write cookies. The following code reads and writes cookies from JS:
// JScript File
/**//*
By codenong. Ken (2007-11-9)
*/
VaR cookie = {
// Read cookies. n is the cookie name.
Get: function (n ){
VaR Re = new Regexp (n + '= ([^;] *);? ', 'Gi ');
VaR r=re.exe C (document. Cookie) | [];
Return (R. length> 1? R [1]: NULL)
},
Get1: function (n ){
VaR Re = new Regexp (n + '= ([^;] *);? ', 'Gi ');
VaR r=re.exe C (document. Cookie) | [];
Return Unescape (R. length> 1? R [1]: NULL)
},
// Write cookies. N indicates the cookie name and V indicates the value.
Set: function (n, V, E, P, D, S ){
VaR T = new date;
If (e ){
// 8.64e7 one day 3.6e6 one hour
T. settime (T. gettime () + (E * 3.6e6 ));

}
Document. Cookie = N + '=' + V + ';' + (! E? '': '; Expires =' + T. toutcstring () + (! P? '': '; Path =' + p) + (! D? '': '; Domain =' + D) + (! S? '': '; Secure') // set cookie
},
Set1: function (n, V, E, P, D, S ){
VaR T = new date;
If (e ){
// 8.64e7 one day 3.6e6 one hour
T. settime (T. gettime () + (E * 8.64e7 ));

}
Document. Cookie = N + '=' + escape (v) + ';' + (! E? '': '; Expires =' + T. toutcstring () + (! P? '': '; Path =' + p) + (! D? '': '; Domain =' + D) + (! S? '': '; Secure') // set cookie
},
DEL: function (N, P, d ){
VaR T = cookie. Get (N );
Document. Cookie = N + '=' + (! P? '': '; Path =' + p) + (! D? '': '; Domain =' + D) + '; expires = Thu, 01-Jan-70 00:00:01 gmt ';
Return t
}
};
// Var totalpro = cookie. Get ("totalpro"); // The total number of items contained in the current car

Next, let's talk about how to operate the shopping cart in JS. Here, the operations required for the shopping cart are: Add a commodity, modify a commodity, and delete a commodity.
These operations have even been directly pasted with code and all have been commented out. If there is any ambiguity, you can reply, and I will try my best to answer the question.

Note: if Javascript itself has cookies with subkeys, there is no need to write the following lines of code!

VaR common = {

// Remove the specified item from the array

Delarr: function (AR, n) {// n indicates the number of items, starting from 0.
If (n <0) // if n <0, no operation is performed.
Return Ar;
Else
Return ar. Slice (0, n). Concat (AR. Slice (n + 1, ar. Length ));
},

// Add to shopping cart
Vehicle car: function (proid, quantity, proname, imgurl, _ price ){
If (proid! = "" & Proname! = ""){
VaR proidlist = cookie. Get ("Carlist"); // In-Vehicle product ID list
If (proidlist! = NULL & proidlist! = "" & Proidlist! = "Null ")
{
If (common. hasone (proid ))
{
Proidlist + = "&" + proid + "=" + proid + "|" + quantity + "|" + escape (proname) + "|" + escape (imgurl) + "|" + _ price;
Cookie. Set ("Carlist", proidlist, 2, "/"); // update the shopping cart list
Totalpro = cookie. Get ("totalpro"); // The total number of items contained in the current car
Totalpro ++; // total + 1
Cookie. Set ("totalpro", totalpro, 2 ,"/");
}
Else
{
Alert ("This item is already included in the shopping cart ");
}
}
Else {

Proidlist = proid + "=" + proid + "|" + quantity + "|" + escape (proname) + "|" + escape (imgurl) + "|" + _ price;
Cookie. Set ("Carlist", proidlist, 2, "/"); // update the shopping cart list

Cookie. Set ("totalpro", 1, 2 ,"/");
}
Common. reloadcar (); // update the top number display
// Alert (proidlist );
}

}, // The end of adding an item

// Reset the number of Shopping Cart items
Reloadcar: function ()
{
VaR T = cookie. Get ("totalpro ");
If (T! = "" & T! = "Null ")
Document. getelementbyid ("cart_num"). innertext = "(" + Cookie. Get ("totalpro") + ")";
Else
Document. getelementbyid ("cart_num"). innertext = "(0 )";
}, // Reset ended

// Check whether the product is included in the shopping cart
Hasone: function (PID ){
Proidlist = cookie. Get ("Carlist"); // In-Vehicle product ID list
If (proidlist. lastindexof ("&")! =-1 ){
VaR arr = proidlist. Split ("&");
For (I = 0; I <arr. length; I ++)
{
// Alert (ARR. indexof ("= "));
If (ARR. substr (0, arr. indexof ("=") = PID)
{

Return false;
}
}
}
Else if (proidlist! = "Null" & proidlist! = "")
{
If (proidlist. substr (0, proidlist. indexof ("=") = PID)
Return false;
}
Return true;
}, // Detection complete

// Remove a product
Removeone: function (proid ){

If (! Common. hasone (proid )){
If (proidlist. lastindexof ("&")! =-1 ){
VaR arr = proidlist. Split ("&");
For (I = 0; I <arr. length; I ++ ){
If (ARR. substr (0, arr. indexof ("=") = proid ){

VaR arr2 = Common. delarr (ARR, I );
VaR tempstr = arr2.join ("&"); // restructured the string from an array

Cookie. Set ("Carlist", tempstr, 2, "/"); // update the shopping cart list
VaR T = cookie. Get ("totalpro ");
Cookie. Set ("totalpro", T-1, 2, "/"); // update the number of cookies
// Common. reloadcar (); // update the top number display
Return;
}
}
}
Else {

Cookie. Set ("Carlist", "null"); // update the shopping cart list
VaR T = cookie. Get ("totalpro ");
Cookie. Set ("totalpro", "/"); // update the shopping cart list
// Common. reloadcar (); // update the top number display
}
}

}, // The End Of The removal is

// Modify the number of items
Updatequantity: function (proid, quantity ){
Proidlist = cookie. Get ("Carlist"); // In-Vehicle product ID list
If (proidlist. lastindexof ("&")! =-1 ){
VaR arr = proidlist. Split ("&");
VaR sub = Common. getsubplace (proidlist, proid); // obtain the subscript position of the item in the cookie Array
VaR arr2 = arr [sub]. Split ("| ");
Arr2 [1] = quantity;
VaR tempstr = arr2.join ("|"); // restructured the string from an array
Arr [sub] = tempstr;
VaR newprolist = arr. Join ("&"); // restructured the string from an array
Cookie. Set ("Carlist", newprolist, 2, "/"); // update the shopping cart list
// Alert (newprolist );
}
Else {

VaR arr = proidlist. Split ("| ");
Arr [1] = quantity;
VaR newprolist = arr. Join ("| ");
Cookie. Set ("Carlist", newprolist, 2, "/"); // update the shopping cart list
// Alert (newprolist );
}

}, // Modify the end of the item

// Returns the subscript position of the array where the specified item is located.
Getsubplace: function (list, proid ){
VaR arr = List. Split ("&");
For (I = 0; I <arr. length; I ++ ){
If (ARR. substr (0, arr. indexof ("=") = proid ){
Return I;
}
}

} // Returns the end Of the subscript.

};


At this point, the core operations of the shopping cart have been completed, and the next step is how to reflect the items in the shopping cart!

Here, I only write ASP. NET to reflect the shopping cart code, ^ _ ^, because other languages are not very familiar with it.

If you have understood the JS Code for adding products to the shopping cart above, you should know how to read the items in the shopping cart. As mentioned above, cookies with subkeys can be grouped in ASP. NET. The structure is similar:
["A1"] ["11111"]
["A1"] ["22222"]
["A1"] ["33333"]
The above A1 is a cookie group, and the next 111,222 is the sub-keys under this group respectively. Previously, our JS stored this way when adding products to cookies. The ID of each item acts as a subkey, and other attributes of the item are the cookies of the subkey. So you may want to ask: how are multiple attributes stored? It is easy to directly separate multiple attribute values with "|.
["Carlist"] ["120"] = "inflatable doll | 5 | 500.50 | cqww.jpg" // similar to this structure

The following code reads all the items in the shopping cart using ASP. NET:

Public arraylist getitems ()
{
Httpcookie c = httpcontext. Current. Request. Cookies ["Carlist"];

Arraylist items = new arraylist ();
For (INT I = 0; I <C. Values. Count; I ++)
{
String [] Vals = C. Values. Split ('| ');
My_shop.model.cshoppingcartitem item = new my_shop.model.cshoppingcartitem ();
Item. productid = int. parse (Vals [0]);
Item. Quantity = int. parse (Vals [1]);
Item. productname = httpcontext. Current. server. urldecode (string) Vals [2]);
Item. imgurl = httpcontext. Current. server. urldecode (string) Vals [3]);
Item. price_s = decimal. parse (Vals [4]);
Items. Add (item );
}
Return items;
}


The my_shop.model.cshoppingcartitem class in the above Code is actually an entity class. To prevent new users from getting confused, we will post the code of the object class below:

Code
Using system;
Namespace my_shop.model
{
Public class cshoppingcartitem: ishoppingcartitem
{
Private int intproductid;
Private string strproductname;
Private string strimgurl;
Private int intquantity;
Private decimal decprice_s;
Public int productid
{
Get
{
Return intproductid;
}
Set
{
Intproductid = value;
}
}
Public String productname
{
Get
{
Return strproductname;
}
Set
{
Strproductname = value;
}
}
Public String imgurl
{
Get
{
Return strimgurl;
}
Set
{
Strimgurl = value;
}
}
Public int quantity
{
Get
{
Return intquantity;
}
Set
{
Intquantity = value;
}
}
Public decimal price_s
{
Get
{
Return decprice_s;
}
Set
{
Decprice_s = value;
}
}
}
}

Oh, the end of the entire drama!

Source: cnblogs
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.