我通过 AJAX 发送 JSOn,它在 servlet 中为 null
JAVASCRIPT
创建 JSON 的函数
function submitTheValues(event, id, price, count) {
var searchEleWithinDiv = document.getElementById("content").children;
var table = searchEleWithinDiv[1];
var qty = table.rows[count].cells[8].children[0].value;
var acNo = table.rows[count].cells[10].children[0].value;
var jsonStr = '{"reagentid": id, "account": acNo,"quantity":
qty, "reagentcount":count}';
var jsonObj = eval("(" + jsonStr + ")");
return jsonObj;
}
AJAX 代码 var xmlhttp = new XMLHttpRequest(); ;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
if(xmlhttp.responseText !=null)
{
var searchEleWithinDiv = document.getElementById("content").children;
var table = searchEleWithinDiv[1];
var btn = table.rows[count].cells[11].children[0].value;
btn.value = "Added to Cart";
}
}
}
var url = "<%=request.getContextPath()%>/displaycartservlet";
var jsonObj = this.submitTheValues(event, id, price, count);
var jsonOb = JSON.stringify(jsonObj);
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.send(jsonOb);
}
如果我将最后两个语句也更改为以下语句,则会收到 null 错误
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencode");
xmlhttp.send('json='+encodeURIComponent(jsonOb));
服务代码
String jsonPar = request.getParameter("json");