[英]How to send a JSON object using html form data
所以我有这个 HTML 表格:
<html>
<head><title>test</title></head>
<body>
<form action="myurl" method="POST" name="myForm">
<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>
</body>
</html>
当用户单击提交时,将这个表单的数据作为 JSON object 发送到我的服务器的最简单方法是什么?
更新:我已经做到了这一点,但它似乎不起作用:
<script type="text/javascript">
function submitform(){
alert("Sending Json");
var xhr = new XMLHttpRequest();
xhr.open(form.method, form.action, true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
var j = {
"first_name":"binchen",
"last_name":"heris",
};
xhr.send(JSON.stringify(j));
我究竟做错了什么?
以数组形式获取完整的表单数据并将其 json 字符串化。
var formData = JSON.stringify($("#myForm").serializeArray());
您可以稍后在 ajax 中使用它。 或者,如果您不使用 ajax; 把它放在隐藏的文本区域并传递给服务器。 如果此数据通过普通表单数据作为 json 字符串传递,那么您必须对其进行解码。 然后,您将获取数组中的所有数据。
$.ajax({
type: "POST",
url: "serverUrl",
data: formData,
success: function(){},
dataType: "json",
contentType : "application/json"
});
HTML 无法从表单数据生成 JSON。
如果您真的想从客户端处理它,那么您将不得不使用 JavaScript 来:
您最好坚持使用application/x-www-form-urlencoded
数据并在服务器上而不是 JSON 上处理它。 您的表单没有任何可以从 JSON 数据结构中受益的复杂层次结构。
更新以响应对问题的重大改写……
readystatechange
处理程序,因此您对响应什么也不做您可以尝试以下方法:
<html>
<head>
<title>test</title>
</head>
<body>
<form id="formElem">
<input type="text" name="firstname" value="Karam">
<input type="text" name="lastname" value="Yousef">
<input type="submit">
</form>
<div id="decoded"></div>
<button id="encode">Encode</button>
<div id="encoded"></div>
</body>
<script>
encode.onclick = async (e) => {
let response = await fetch('http://localhost:8482/encode', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
})
let text = await response.text(); // read response body as text
data = JSON.parse(text);
document.querySelector("#encoded").innerHTML = text;
// document.querySelector("#encoded").innerHTML = `First name = ${data.firstname} <br/>
// Last name = ${data.lastname} <br/>
// Age = ${data.age}`
};
formElem.onsubmit = async (e) => {
e.preventDefault();
var form = document.querySelector("#formElem");
// var form = document.forms[0];
data = {
firstname : form.querySelector('input[name="firstname"]').value,
lastname : form.querySelector('input[name="lastname"]').value,
age : 5
}
let response = await fetch('http://localhost:8482/decode', {
method: 'POST', // or 'PUT'
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
let text = await response.text(); // read response body as text
document.querySelector("#decoded").innerHTML = text;
};
</script>
</html>
我迟到了,但我需要对那些需要对象的人说,只使用 html,有一种方法。 在一些服务器端框架(如 PHP)中,您可以编写以下代码:
<form action="myurl" method="POST" name="myForm">
<p><label for="first_name">First Name:</label>
<input type="text" name="name[first]" id="fname"></p>
<p><label for="last_name">Last Name:</label>
<input type="text" name="name[last]" id="lname"></p>
<input value="Submit" type="submit">
</form>
因此,我们需要将输入的名称设置为object[property]
以获得一个对象。 在上面的示例中,我们得到了一个带有以下 JSON 的数据:
{
"name": {
"first": "some data",
"last": "some data"
}
}
您的代码很好但从未执行过,提交按钮的原因 [type="submit"] 只需将其替换为type=button
<input value="Submit" type="button" onclick="submitform()">
在你的脚本里面; 没有声明形式。
let form = document.forms[0];
xhr.open(form.method, form.action, true);
formData= new FormData(form)
捕获表单数据JSON.stringify(Object.fromEntries(formData))
将其转换为 JSONvar form = document.getElementById('myForm');
form.onsubmit = function(event){
var xhr = new XMLHttpRequest();
var formData = new FormData(form);
//open the request
xhr.open('POST','http://localhost:7000/tests/v1.0/form')
xhr.setRequestHeader("Content-Type", "application/json");
//send the form data
xhr.send(JSON.stringify(Object.fromEntries(formData)));
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
form.reset(); //reset form after AJAX success or do something else
}
}
//Fail the onsubmit to avoid page refresh.
return false;
}
摘自我在这里写的一篇文章: https ://metamug.com/article/html5/ajax-form-submit.html
所以我有这个HTML表单:
<html>
<head><title>test</title></head>
<body>
<form action="myurl" method="POST" name="myForm">
<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>
</body>
</html>
当用户单击“提交”时,哪一种是将此表单的数据作为JSON对象发送到我的服务器的最简单方法?
更新:我已经走了这么远,但似乎没有用:
<script type="text/javascript">
function submitform(){
alert("Sending Json");
var xhr = new XMLHttpRequest();
xhr.open(form.method, form.action, true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
var j = {
"first_name":"binchen",
"last_name":"heris",
};
xhr.send(JSON.stringify(j));
我究竟做错了什么?
微型库字段辅助正是这样做的: collectValues(formElement)
将从输入字段返回一个规范化的 json(这也意味着,复选框作为布尔值,选择作为字符串等)。
如果你想在2022年使用纯javascript...
const ajax = async (config) => {
const request = await fetch(config.url, {
method: config.method,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(config.payload)
});
response = await request.json();
console.log('response', response)
return response
}
// usage
response = ajax({
method: 'POST',
url: 'example.com',
payload: {"name": "Stackoverflow"}
})
我找到了一种仅使用 HTML 表单来传递 JSON 消息的方法。
此示例适用于 GraphQL,但它适用于任何需要 JSON 消息的端点。
GrapqhQL 默认需要一个称为操作的参数,您可以在其中添加 JSON 格式的查询或突变。 在这种特定情况下,我正在调用此查询,该查询请求获取 allUsers 并返回每个用户的 userId。
{
allUsers
{
userId
}
}
我正在使用文本输入来演示如何使用它,但您可以将其更改为隐藏输入以向用户隐藏查询。
<html>
<body>
<form method="post" action="http://localhost:8080/graphql">
<input type="text" name="operations" value="{"query": "{ allUsers { userId } }", "variables": {}}"/>
<input type="submit" />
</form>
</body>
</html>
为了使这种动态化,您需要 JS 在提交表单之前将文本字段的值传输到查询字符串。 无论如何,我发现这种方法非常有趣。 希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.