php - 从表单数据中获取 JSON
问题描述
我正在编写一个代码来获取使用表单发送的 JSON 参数。
我有这个 html
<form action="jsonfile.php" method="POST" name="myForm" enctype="application/json">
<p><label for="first_name">First Name:</label>
<input type="text" name="first_name" id="fname"></p>
<p><label for="last_name">Last Name:</label>
<input type="text" name="last_name" id="lname"></p>
<input value="Submit" type="submit" onclick="submitform()">
</form>
和这里的 json
<script>
var formData = JSON.stringify($("#myForm").serializeArray());
$.ajax({
type: "POST",
url: "jsonfile.php",
data: formData,
dataType: "json",
contentType : "application/json",
success: function(result){
}
});
</script>
现在,我想在另一个名为JSONFILE.PHP的文件中将上述表单的值作为 json 发送。我真的不知道应该用什么将数据装饰成 JSON DATA。
谢谢你。
解决方案
// HTML Code
<form method="POST" name="myForm" id="myForm" enctype="application/json" onsubmit="return false">
<p><label for="first_name">First Name:</label>
<input type="text" name="first_name" id="fname"></p>
<p><label for="last_name">Last Name:</label>
<input type="text" name="last_name" id="lname"></p>
<input value="Submit" type="submit" >
</form>
// JavaScript Code
<script>
$("#myForm").submit(function () {
var formData = JSON.stringify($("#myForm").serializeArray());
$.ajax({
type: "POST",
url: "jsonfile.php",
data: formData,
dataType: "json",
contentType: "application/json",
success: function (result) {
}
});
});
</script>
// PHP Code jsonfile.php
<?php
$data = json_decode(file_get_contents('php://input'), true);
if ($data) {
print_r($data);
}
?>
推荐阅读
- kubernetes - 在 Mirantis Openstack 上部署 Kubernetes 集群覆盖失败
- sql-server - 如何在 SELECT UNION 语句 SQL Server 中添加表指示符
- javascript - 具有启用 JavaScript 效果的导航菜单
- python - pd.to_numeric 无法将字符串转换为浮点数
- .net-core - CloudFoundry 应用程序实例 - EF Core 数据库迁移
- haskell - 如何在 ghci 中调用具有特定数据结构的函数
- javascript - 将 PHP 变量中的日期设置为 daterangepicker
- visual-studio - Power BI 2021 年 5 月启动错误:AS 进程 PID = 16228 已退出,ExitCode=-1073741792,ExitTime=____
- reactjs - 如何实现材料表以与我的 api 一起使用,这将允许我转到下一页
- c++ - 用向量制作一个矩阵