[英]Convert form data to json before sending with ajax
我正在嘗試將表單數據轉換為 JSON 以使用 Jquery 發送。 我知道這個問題已經被問過很多次了,到目前為止這是我找到的最好的答案
https://stackoverflow.com/a/11339012/492015
從上面的鏈接回答
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;
}
用法:
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
{comment: "This is a comment", country: "us"}
有沒有一種簡單的方法可以將表單數據轉換為有效的 JSON? 我正在嘗試生成以下 JSON 格式
{"comment": "This is a comment", "country": "us"}
以下是 Javascript Object。 它不是 JSON。 要將其轉換為 JSON,您可以使用JSON.stringify(object)
function。
{comment: "This is a comment", country: "us"}
以下是如何將 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.