jquery - 使用 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 代码不是这种情况。
解决方案
我看不出你的代码有什么问题。我尝试将它输入到代码片段中,它工作得很好。
我只是把你<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/json
header,并将请求类型设置为POST
推荐阅读
- string - 如何在一个长字符串中搜索一个值?
- javascript - 在 Javascript 中分配事件以显示在 HTML 检查器中
- javascript - 如何使用 jQuery 创建循环
- php - 如何从 Prestashop 1.7.6 中的表 stock_available 获取数量
- angular - 如何构建角度应用程序
- google-cloud-platform - 在 GCP 中将数据从 VM 实例传输到 BigQuery
- r - 如何在插入符号或 tidymodels 中使用 LASSO 进行嵌套交叉验证?
- r - 使用鼠标输入大型数据帧时出错
- c# - 为什么在通过 dotnet CLI 运行 ASP.NET Core 应用程序时看到项目目录名称而不是 dotnet(进程外)?
- flutter - AppBar内的后退按钮在颤动中显示黑屏