用vue和node写的简易购物车实现(2)

add_to_cart:function (e) { let item_id = parseInt(e.currentTarget.getAttribute('data-id'));//vue获取当前dom对象 let data = {id:2333,item_id:item_id}; $.ajax({ type: "post", url: "/add_to_cart", dataType: "json", data: JSON.stringify(data), contentType: 'application/json', success: function (response) { if(response.errcode ===1 ){ console.log('加入购物车成功'); let div = document.createElement('div'); div.setAttribute('class','item'); div.setAttribute('data-id',item_id); let img_src; if(e.target.nodeName==='IMG'){ img_src = e.target.getAttribute('src'); }else if(e.target.nodeName==='SPAN'){ img_src = e.target.previousSbiling.getAttribute('src'); } let str = '<div> 'https://www.jb51.net/article/+'<img src="'+ img_src +'">' + '</div><span>test1</span>'https://www.jb51.net/article/+'<div>' +'<p>删除</p>'+ '</div>'; div.innerHTML = str; document.getElementById('content_right').appendChild(div); }else if(response.errcode ===2){ alert('已经添加过了哦'); } }, error: function (request) { } }); }

my_server.js接收请求 

app.post('/add_to_cart', function (req, res) { let request = req.body; let query = 'SELECT f_uid,f_item_id FROM t_item_user WHERE f_item_id = ?'; let query_param = request.item_id; conn.query(query,query_param, function (err2, rows) { if (err2) console.log(err2); if(rows.length===0){ //insert let sql = 'insert into t_item_user(f_uid,f_item_id) values(?,?)'; let param = [req.body.id,req.body.item_id]; conn.query(sql,param, function (err1, res1) { if(res1.affectedRows==1){ let $return={ errcode:1, errmsg:'插入成功', }; res.end(JSON.stringify($return)); }else{ console.log('what'); } }) }else{ let $return={ errcode:2, errmsg:'该商品已经存在', }; res.end(JSON.stringify($return));//返回 } }) });

github:https://github.com/yunhongyao/simple_shopping_cart

完整代码下载:simple_shopping_cart_jb51.rar

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wypdyw.html