我有一个HTML代码,它是一个包含2行(可能更多)的表单,以及一个通过RESTAPI将每行元素发送到服务器的javascript。我无法让它发挥作用。尝试调试它没有向我显示任何错误或响应。有人可以看看我的代码!谢谢!
<html><body>
<form id='myform' method='post'>
<table>
<tr>
<td><input type=text name=firstName></td>
<td><input type=text name=email></td>
</tr>
<td><input type=text name=firstName></td>
<td><input type=text name=email></td>
</tr>
<tr><td><input type=submit></td></tr>
</table>
</form>
</body></html>
<script>
var myForm = document.getElementById('myform');
myForm.onsubmit = function(event) {
event.preventDefault();
var request = new XMLHttpRequest();
request.open('POST', 'https://localhost/api', true);
function myFunction(){
for(var i=0;i<myForm.length;i++){
var formData = new FormData(document.getElementById('myform').rows[i]);
request.send(formData);
}
}
request.onload = function () {
console.log(request.response);
};
}
答案 0 :(得分:0)
您在HTML中错误拼写了表单元素ID。
将<form id='myfrom' method='post'>
更改为<form id='myform' method='post'>
。
您还需要关闭</script>
代码
答案 1 :(得分:0)
如果您正在使用我推荐的jQuery,请执行以下操作:
<html>
<body>
<form id='myform'>
<table>
<tr>
<td><input type="text" name="items[0].FirstName"></td>
<td><input type=text name="items[0].Email"></td>
</tr>
<td><input type=text name="items[1].FirstName"></td>
<td><input type=text name="items[1].Email"></td>
</tr>
<tr><td><input type=submit></td></tr>
</table>
</form>
<script type="text/javascript">
$(document).ready(function() {
$('#myform').submit(function() {
$.ajax({
url: 'http://localhost/api/saveitems',
type: 'POST',
data: $('#myform').serialize()
}).done(function(data) {
// check your returned data for success
});
});
});
</script>
</body>
</html>
在服务器端,这将需要一些东西。首先,您需要创建一个包含您传入的字段的类,例如:
public class Item {
public string FirstName {get; set;}
public string Email {get; set;}
}
然后,您需要在您的应用程序中拥有一个接收项目列表的API端点:
[HttpPost]
public ActionResult SaveItems(List<Item> items) {
// Do whatever you need to do
return Json("success", JsonRequestBehavior.AllowGet);
}