[英]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.