简体   繁体   English

在使用 ajax 发送之前将表单数据转换为 json

[英]Convert form data to json before sending with ajax

I am trying to convert form data to JSON to be sent using Jquery.我正在尝试将表单数据转换为 JSON 以使用 Jquery 发送。 I understand that this has been asked many times on SO, so far this is the best answer I have found我知道这个问题已经被问过很多次了,到目前为止这是我找到的最好的答案

https://stackoverflow.com/a/11339012/492015 https://stackoverflow.com/a/11339012/492015

Answer from link above从上面的链接回答

function getFormData($form){
    var unindexed_array = $form.serializeArray();
    var indexed_array = {};

    $.map(unindexed_array, function(n, i){
        indexed_array[n['name']] = n['value'];
    });

    return indexed_array;
}

Usage:用法:

var $form = $("#form_data");
var data = getFormData($form);

However this is producing invalid JSON according to https://jsonlint.com also Spring Boot is not accepting it as valid JSON since there are no double quotes around comment and country However this is producing invalid JSON according to https://jsonlint.com also Spring Boot is not accepting it as valid JSON since there are no double quotes around comment and country

{comment: "This is a comment", country: "us"}

Is there a simple way to convert form data to valid JSON?有没有一种简单的方法可以将表单数据转换为有效的 JSON? I am trying to generate the following JSON format我正在尝试生成以下 JSON 格式

{"comment": "This is a comment", "country": "us"}

The following is a Javascript Object.以下是 Javascript Object。 It is not JSON.它不是 JSON。 To convert it to JSON, you can use JSON.stringify(object) function.要将其转换为 JSON,您可以使用JSON.stringify(object) function。

{comment: "This is a comment", country: "us"}

Here is an example how to convert a JavaScript object to JSON.以下是如何将 JavaScript object 转换为 JSON 的示例。

 let jsObject = {comment: "This is a comment", country: "us"}; document.write(JSON.stringify(jsObject));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM