文章将通过以下代码显示,文章ID通过URL输入。
现在是我的问题,我想使用Ajax将id / price推送到servlet,然后servlet在所有相关站点上添加/更新Shopping cart。 被记录的日志为用户提供了会话
但是我的servlet不接收任何数据,会话属性总是带有NULL。
<script src="js/islogged.js" type="text/javascript"></script>
<script>
if (location.search.length > 1) {
var nr = location.search.substring(1, location.search.length);
nr = unescape(nr);
}
$.ajax({
type: "GET",
url: "./Article",
data: { pid: nr},
contentType: "application/x-www-form-urlencoded",
success: function(data) {
$('#Price').html(data.productPrice + " €");
var stern = "";
for(var i=0; i < data.rating; i++) {
stars= stars+ "★ ";
}
for(var i=data.rating; i < 5;i++) {
stars= stars+ "☆"
}
$('#test').append("<h2 class=\"section-heading\">" + data.prductName + "</h2>" + //productName
"<div hidden id=\"Articlenumber\">" + data.id + "</div>" +
"<hr class=\"my-4\">" +
"<p class=\"mb-5\">" + stars+ "</p>" +
"<p class=\"mb-5\">" + data.productDescription + "</p>" +
"");
},
error: function(jqXHR, textStatus, errorThrown) {
// not implemented right now
alert("Error");
}}
)
该网站显示商品说明,我将商品ID /价格用于购物车。
我可以更改页面上的文章数量,但其他所有内容均保持不变。当我点击“提交”时,我想在购物车中添加商品名称/编号和价格
<p align="center">
<div>
<div class="text-center">
<h3 align="center"><div class="Price" id="Price">0€</div></h3>
<p>+ Shipping Costs</p>
</div>
</div>
<div>
<div class="profil" adding="profiletextbox">
<p align="center">
<input id="a" value="1" min="1" type="number"> Stück
</p>
</div>
</div>
<div class="text-center">
<form><input id="add" type="submit" class="btn btn-primary btn-xl js-scroll-trigger" value="Submit" /></form>
</div>
</p>
这是我精心制作的用于将数据获取到servlet的方法(它直接在上面显示的ajax下)
$("#add").click(function(){
$.ajax
(
{
type:"GET",
url:"./ShoppingCart",
data:{id: nr, anz: a},
success:function(data){alert(data);},
error:function(){alert('errorpushtoservlet');}
}
);
}
我的ShoppingCart.java,我只是为了安全起见检查了会话,但没有任何问题。
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class ShoppingCart extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(false);
//int nr = Integer.parseInt(request.getParameter("nr"));
String anz = request.getParameter("anz");
String nr = request.getParameter("id");
String id = String.valueOf(session.getAttribute(nr));
String count = String.valueOf(session.getAttribute(anz));
session.setAttribute("id", id);
session.setAttribute("count", count);
System.out.println("print1: "+request.getSession().getId());
System.out.println("id2 = " + id);
System.out.println("anz = " + anzahl);
}
}