Convert to 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 cart is indispensable in the mall system. According to observation, most online mallsProgramThe shopping cart is a simple storage method to implement the shopping cart, 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?
Fang
Database, session, cookies ......, Most of my friends may choose databases. I chose cookies because the shopping cart is only used to buy products for users.
It provides a convenient centralized container. Since it is for temporary use, why bother driving 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 this "cookies.
how to operate cookies to implement shopping cart?
In other words, try to reduce the pressure on the server, since the client's stuff is stored, we can also use the client's stuff for operations, that is, JavaScript. Well, JavaScript can directly read and write cookies. The following code reads and writes cookies from javascript:
// JScript file
/** // *
by country. ken (2007-11-9)
*/
var cookie = {
// read cookies. n is the cookie name.
Get: function (N) {
var Re = new Regexp (n + '= ([^;] *);? ', 'Gi');
var rw.re.exe C (document. Cookie) | [];
return (R. length> 1? R [1]: NULL)
},
get1: function (n) {
var Re = new Regexp (n + '= ([^;] *);? ', 'Gi');
var rw.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 are directly pasted.CodeI have made comments. If you have any questions, I can reply to them.

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"]
Upper
A1 is a cookie group, and the next 111,222 is the sub-keys under this group. Previously, our JS stored the cookies when adding products to the group. Each
The item ID is used 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's easy to directly put multiple attribute values
Separated by "|.
["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;
}
}
}
}

 

original address: http://www.cnblogs.com/jianshao810/archive/2010/05/14/1735453.html

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.