【发布时间】:2014-05-22 09:04:28
【问题描述】:
我想借助 JSON 将一些数据从 JavaScript 发送到 Java servlet。但我有问题。
这是我的 JavaSript 代码:
var myData = {"someNumber":34,"someDate":"May 22, 2014 12:00:00 AM","expiryDate":"May 29, 2014 12:00:00 AM","anotherNumber":3,"customerNumber":56,"name":"John Dow","type":"notype","someSize":"XXL","noMonth":11,"notes":"some notes here","colour":"Black"};
$.ajax({
url : "customerAdd",
type: "get",
data: {"myData" : JSON.stringify(myData)},
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(msg) {
alert(msg);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("jqXHR: " + textStatus);
console.log("textStatus: " + textStatus);
console.log("errorThrown: " + errorThrown);
}
});
这是我的 Java 代码:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{
Gson gson = new GsonBuilder().create();
Customer customer = gson.fromJson(request.getParameter("myData"), Customer.class);
System.out.println(customer.toString());
}
结果我在 JavaScript 中得到一个错误:
"textStatus: parsererror"
"errorThrown: SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data"
我的代码有什么问题?
附: 我通过这种方式在 JavaScript 中创建 myData:
var myData = {
someNumber: + $("#someNumber").val(),
someDate: $("#someDate").val(),
expiryDate: $("#expiryDate").val(),
anotherNumber: + $("#anotherNumber").val(),
customerNumber: + $("#customerNumber").val(),
name: $("#name").val(),
type: $("#type").val(),
someSize: $("#someSize").val(),
noMonth: + $("#noMonth").val(),
notes: $("#notes").val(),
colour: $("#colour").val() };
【问题讨论】:
标签: java javascript jquery json servlets