我正在一个html页面上工作,该页面应该将带有请求正文的发布请求提交到我的服务器,如下所示
<html>
<head>Customer app</head>
<body>
<div>
<table>
<tr>
<td>Customer Id :</td>
<td>
<form name="submitform" method="post">
<input type="text" id="customerId" name="customerId"/>
<input type="submit" value="Submit">
</form>
</td>
</tr>
</table>
</div>
</body>
<script>
$(document).ready(function(){
$("#submitform").click(function(e)
{
var MyForm = JSON.stringify($("#customerId").serializeJSON());
console.log(MyForm);
$.ajax({
url : "http://localhost:7777/ola-drive/customer/ride",
type: "POST",
data : MyForm,
});
e.preventDefault(); //STOP default action
});
});
</script>
</html>
不能正常工作,抛出404 Not Found被重定向到http://localhost:7777/customerapp.html。但是与请求提交相对应的表单数据似乎是正确的。
有人可以帮助我解决html代码提交POST请求重定向的问题吗?
最佳答案
您的问题在以下行中:
$("#submitform").click(function(e)
您的表单没有ID,而是名称,因此您可以编写:
$('[name="submitform"]').click(function(e)
这是因为您的表单给您重定向错误。
$('[name="submitform"]').click(function (e) {
e.preventDefault();
$.ajax({
url: "http://localhost:7777/ola-drive/customer/ride",
type: "POST",
data: {"customerId": $("#customerId").val()},
success: function (result) {
//do somthing here
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<table>
<tr>
<td>Customer Id :</td>
<td>
<form name="submitform" method="post">
<input type="text" id="customerId" name="customerId"/>
<input type="submit" value="Submit">
</form>
</td></tr>
</table>
</div>
关于javascript - 通过HTML表单使用请求正文发出发布请求,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45663284/