背景和问题
想实现的功能是加入购物车,多次点击加入购物车按钮,商品都能加入购物车。
目前的问题是如果在商品列表页面,刷新一下,就可以连续一直提交。如果在导航栏切换到别的页面,在切换回来,就点击按钮无效了。必须刷新一下当前页(商品列表页)才能添加。
环境
ruby on rails
bootstrap
jquery
调试信息
在出问题的时候,观察浏览器调试inspect, network和console都没有任何信息输出。
服务端无log
怀疑点
下面有朋友提到的。可能是前端什么地方出了问题,避免了重复提交。
其他网站的实现
亚马逊为例,可以多次点击
加入购物车
按钮,是用form实现的。
https://www.amazon.cn/s/ref=nb_sb_noss_1?__mk_zh_CN=%E4%BA%9A%E9%A9%AC%E9%80%8A%E7%BD%91%E7%AB%99&url=search-alias%3Daps&field-keywords=ruby
京东为例,可以多次点击
加入购物车
按钮,是用get请求实现的。
href="//cart.jd.com/gate.action?pid=11524040&pcount=1&ptype=1"
京东的每一个商品,事先会生成一个href,pid应该就是商品ID,但是感觉这种实现并不符合REST传统。
为什么表单提交之后,如果后退回来,再点击提交,就没有反应了?
只有再刷新页面后,再点击,才能再次提交。
前端代码片段
<table class="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>Price</th>
<th>Show</th>
<th>Edit</th>
<th>Destroy</th>
<th>Amount</th>
<th>购买</th>
<th colspan="5"></th>
</tr>
</thead>
<tbody>
<tr>
<form action="/carts" method="post" target="_blank">
<td>西红柿</td>
<td>西红柿</td>
<td>30.0</td>
<td><a href="/products/1">Show</a></td>
<td><a href="/products/1/edit">Edit</a></td>
<td><a data-confirm="Are you sure?" rel="nofollow" data-method="delete" href="/products/1">Destroy</a></td>
<input name="cart[product_id]" value="1" type="hidden" />
<input name="cart[user_id]" value="2" type="hidden" />
<td><input type="number" name="cart[amount]" required="true" max="100" ></td>
<td><button type="submit" class="btn btn-primary">加入购物车</button></td>
</form>
</tr>
<tr>
<form action="/carts" method="post" target="_blank">
<td>土豆</td>
<td>土豆</td>
<td>30.0</td>
<td><a href="/products/2">Show</a></td>
<td><a href="/products/2/edit">Edit</a></td>
<td><a data-confirm="Are you sure?" rel="nofollow" data-method="delete" href="/products/2">Destroy</a></td>
<input name="cart[product_id]" value="2" type="hidden" />
<input name="cart[user_id]" value="2" type="hidden" />
<td><input id="inputAmount" type="number" name="cart[amount]" required="true" max="100" ></td>
<td><button type="submit" class="btn btn-primary">加入购物车</button></td>
</form>
</tr>
</tbody>
</table>
应该是有一种机制 避免了 表单反复提交的问题,这样必须刷新之后才可以重新提交。
可以通过查看服务器端Log验证这个想法~