使用query.serializeJSON序列化表单数据



我已经按照前面的答案使用这个包将表单数据转换为JSON

<main>

<form id="myform" action="/form" method="post">
Name: <input type="text" name="name"><br>
email: <input type="text" name="email"><br>
message: <input type="text" name="message"><br>
<input type="submit" value="Submit">
</form>

<div id='response'></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.serializeJSON/2.9.0/jquery.serializejson.min.js"></script>
<script>
$('#myform').serializeJSON();
</script>
</body>
</html>

我确信我错过了一些琐碎的事情。我需要post-to/form传递的数据是JSON,而aboce代码不是这样。

我认为您的代码没有任何错误。我试着把它输入到代码片段中,它运行得很好。

我只把你的<main>换成了<html><body>

<html>
<body>
<form id="myform" action="/form" method="post">
Name: <input type="text" name="name" value="namevalue"><br>
email: <input type="text" name="email" value="emailvalue"><br>
message: <input type="text" name="message" value="messagevalue"><br>
<input type="submit" value="Submit">
</form>
<div id='response'></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.serializeJSON/2.9.0/jquery.serializejson.min.js"></script>
<script>
//console.log($('#myform').serializeJSON());
$("#myform").submit(function(){
console.log($('#myform').serializeJSON());

$.ajax({
type: "POST",
url: "https://webhook.site/9b058239-03ad-49d2-9e0e-6c6be1bfe20b",
data: JSON.stringify($('#myform').serializeJSON()),
success: function(data){alert("success posting!"+data);},
error: function(data){alert("error posting!"+data);},
contentType: "application/json"
});
return false;
});
</script>
</body>
</html>

编辑:我使用webhook.site来测试POST后的JSON。它按预期工作。

它在这里(它与片段一起工作(:https://webhook.site/#/9b058239-03ad-49d2-9e0e-6c6be1bfe20b/01154f2c-ac5b-426d-b68c-5959e6bf9941/1

如果您无法读取服务器端的数据,请检查您是否添加了Content-Type: application/json标头,并将请求类型设置为POST

最新更新