[英]How do I send HTML form data to JSON using javascript (without jquery)?
On submit, I want to send form data to json.提交时,我想将表单数据发送到 json。 I want to use json so I can send the data to Python for processing.
我想使用 json 以便我可以将数据发送到 Python 进行处理。 I am not using jquery.
我没有使用 jquery。
I have the following HTML code:我有以下 HTML 代码:
<form id="frm1">
<label for="first">First name: <input type="text" id="first" name="first"></label><br><br>
<label for="last">Last name: <input type="text" id="last" name="last"></label><br>
<input type="submit" value="Submit">
</form>
I attempted to send the data to JSON using the following JS code:我尝试使用以下 JS 代码将数据发送到 JSON:
form.addEventListener('submit', sendData)
function sendData(event){
//retreives form input
const first = form.querySelector('input[name="first"]');
const last = form.querySelector('input[name="last"]');
var xhr = new XMLHttpRequest();
var url = "formResults.json";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.first+ ", " + json.last);
}
};
var data = JSON.stringify({first, last});
xhr.send(data);
}
I am running the code in a local server and am seeing no output to the json file or any error code.我在本地服务器上运行代码,但没有看到 json 文件的输出或任何错误代码。
How do I get my form data to json?如何将我的表单数据转换为 json?
Novice coder新手编码员
This really is quite an open question.这确实是一个相当悬而未决的问题。 You have provided no details on the model in which the data needs to be provided as.
您没有提供有关需要提供数据的模型的详细信息。 I'm going to assume you need an object similar to the below.
我假设你需要一个类似于下面的对象。
{
first: 'John',
last: 'Smith'
}
If this is the case, you could use the below code.如果是这种情况,您可以使用以下代码。
var serializeForm = function (form) {
// Setup our serialized data
var serialized = {};
// Loop through each field in the form
for (var i = 0; i < form.elements.length; i++) {
var field = form.elements[i];
// Don't serialize fields without a name, submits, buttons, file and reset inputs, and disabled fields
if (!field.name || field.disabled || field.type === 'file' || field.type === 'reset' || field.type === 'submit' || field.type === 'button') continue;
// If a multi-select, get all selections
if (field.type === 'select-multiple') {
for (var n = 0; n < field.options.length; n++) {
if (!field.options[n].selected) continue;
serialized[field.name] = field.options[n].value
}
}
// Convert field data to a query string
else if ((field.type !== 'checkbox' && field.type !== 'radio') || field.checked) {
serialized[field.name] = field.value
}
}
return serialized;
};
Then you could use your code ...然后你可以使用你的代码......
form.addEventListener('submit', sendData)
function sendData(event){
//retreives form input
const formData = serializeForm(form);
var xhr = new XMLHttpRequest();
var url = "YOUR_ENDPOINT_NEEDS_TO_GO_HERE";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log(json);
}
};
var data = JSON.stringify(formData);
xhr.send(data);
}
You can see the above using the codepen linked here .你可以在上面看到使用链接的codepen在这里。 In the example, the object is created immediately, so right-click anywhere in the preview window, view console and you'll see the output of the serializeForm method.
在示例中,对象是立即创建的,因此右键单击预览窗口中的任意位置,查看控制台,您将看到 serializeForm 方法的输出。
Credit goes to: https://gomakethings.com/how-to-serialize-form-data-with-vanilla-js/ where I got the initial code from and modified it to your (assumed) needs.归功于: https : //gomakethings.com/how-to-serialize-form-data-with-vanilla-js/ ,我从中获取了初始代码并将其修改为您的(假设)需求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.