首页 > 解决方案 > 使用 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 传递到 /form 的数据是 JSON,而 aboce 代码不是这种情况。

标签: jquery

解决方案


我看不出你的代码有什么问题。我尝试将它输入到代码片段中,它工作得很好。

我只是把你<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'ed JSON。它按预期工作。

在这里(它适用于片段):https ://webhook.site/#!/9b058239-03ad-49d2-9e0e-6c6be1bfe20b/01154f2c-ac5b-426d-b68c-5959e6bf9941/1

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


推荐阅读