简体   繁体   English

如何使用 javascript(不使用 jquery)将 HTML 表单数据发送到 JSON?

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

相关问题 如何在没有JavaScript,jquery或HTML表单的情况下将数据发送到另一个页面? - How can I send data to another page without javascript, jquery, or an HTML form? 如何使用jquery / javascript &amp;&amp;重置html中的表单数据,以及如何使用jquery将表单数据发送到电子邮件? - How to reset the form data in html using jquery/javascript && and also how to send the form data to an email using jquery? 如何在不使用服务器端语言的情况下从 HTML 表单存储/发送数据? - How do I store/send data from a HTML form without using a server side language? 如何通过HTML表单输入文本并使用Javascript从JSON文件中检索数据作为响应? - How do I input text via an HTML form and retrieve data from a JSON file as a response using Javascript? 如何使用Javascript或Jquery将一系列JSON数据附加到HTML? - How do I append a range of JSON data to my HTML using Javascript or Jquery? 如何将 JSON 文件数据显示到 HTML 表中(仅使用 JavaScript,而不是 jQuery) - How do I display JSON file data into HTML table (using JavaScript only, not jQuery) 如何使用Javascript输出HTML表单数据? - How do I output HTML form data using Javascript? 如何使用jquery ajax发送表单数据而不提交表单? - How to send form data using jquery ajax without submitting the form? 如何使用JavaScript将HTML表单值发送到JSON字符串中的localstorage - How to send HTML form values to localstorage in JSON string using JavaScript HTML / Javascript表单如何将表单数据序列化为JSON并在类中显示? - HTML/Javascript Form How do I serialize form data as JSON and displayed in a class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM