[英]No JSON object gets passed when using $.ajax() function call in jQuery
我編寫了這段代碼是為了從HTML表中捕獲用戶輸入的數據,然后使用ajax將其傳遞給后端。 請注意,在以下代碼中調用$.ajax()
函數之前,我能夠看到控制台的輸出,這意味着第15行之前的任何代碼均能正常工作。 屏幕截圖是代碼行15的輸出:
$('form').submit( //line 1
function(e) { //line 2
e.preventDefault(); //line 3
var header = $('table thead tr th').map(function() { //line 4
return $(this).text(); //line 5
}); //line 6
var tableObj = $('table tbody tr').map(function(i) { //line 7
var row = {}; //line 8
$(this).find('td').each(function(i) { //line 9
var rowName = header[i]; //line 10
row[rowName] = $(this).find("input").val(); //line 11
}); //line 12
return row; //line 13
}).get(); //line 14
console.log(tableObj); //line 15
$.ajax({
url:"/spring-mvc-webapp/jsondata",
type:'POST',
data :JSON.stringify(tableObj),
dataType: "json",
contentType : 'application/json; charset=utf-8',
success:function(result){console.log(result);},
error: function (jqXHR, textStatus, errorThrown) {
alert("jqXHR: " + jqXHR.status + "\ntextStatus: " + textStatus + "\nerrorThrown: " + errorThrown);
}
});//end ajax
}
);
我從更改框收到此錯誤消息:
jqXHR:200
textStatus:parsererror
errorThrown:SyntaxError:輸入意外結束
這是HTML:
<form action="/spring-mvc-webapp/jsondata" method="post">
<table>
<thead>
<tr>
<th>Gross Weight</th>
<th>Tare Weight</th>
<th>Price Per Pound</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" /></td>
<td><input type="text" /></td>
<td><input type="text" /></td>
</tr>
<tr>
<td><input type="text" /></td>
<td><input type="text" /></td>
<td><input type="text" /></td>
</tr>
</tbody>
</table>
<input type="submit" />
</form>
我沒有包含后端Java代碼,因為我已經知道$.ajax()
不能正常工作,如果您認為有必要,我將添加后端代碼。
誰能告訴我我做錯了什么? 為什么沒有$.ajax()
發布JSON
數據?
您應該直接將數據作為JSON發送:
$.ajax({
url:"/spring-mvc-webapp/jsondata",
type:'POST',
data :tableObj,
dataType: "json",
contentType : 'application/json; charset=utf-8',
success:function(result){console.log(result);},
error: function (jqXHR, textStatus, errorThrown) {
alert("jqXHR: " + jqXHR.status + "\ntextStatus: " + textStatus + "\nerrorThrown: " + errorThrown);
}
});//end ajax
或發送包含序列化數據的JSON:
$.ajax({
url:"/spring-mvc-webapp/jsondata",
type:'POST',
data : { data: JSON.stringify(tableObj) },
dataType: "json",
contentType : 'application/json; charset=utf-8',
success:function(result){console.log(result);},
error: function (jqXHR, textStatus, errorThrown) {
alert("jqXHR: " + jqXHR.status + "\ntextStatus: " + textStatus + "\nerrorThrown: " + errorThrown);
}
});//end ajax
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.