gpt4 book ai didi

javascript - 创建 JSON 字符串以发布到 jQuery/Javascript 中的网络服务

转载 作者:行者123 更新时间:2023-11-30 14:50:39 25 4
gpt4 key购买 nike

我有一个 html 表单、一个按钮和一个点击处理程序来管理表单的提交。问题具体是关于通过 AJAX 提交表单的按钮的处理程序。

这是我写的处理程序:

JS:

            $('#create').click(function(event) {
console.log('Create Button Click');
var dataJSON = JSON.stringify( $('#customer_form').serializeArray() );
console.log(dataJSON);
$.ajax({
type: "POST",
url: "/customer/",
// The key needs to match your method's input parameter (case-sensitive).
data: dataJSON,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
console.log('Success');
console.log(data);
},
failure: function(errMsg) {
console.log('Error');
console.log(errMsg);
}
});
event.preventDefault();
});

我使用 JSON.stringify( $('#customer_form').serializeArray() ); 生成 JSON 字符串,得到结果 - 如 console.log(数据JSON):

[{"name":"name","value":"n"},{"name":"address_line_1","value":"a1"},{"name":"address_line_2","value":"a2"},{"name":"town","value":"t"},{"name":"postal_code","value":"p"},{"name":"region","value":"r"},{"name":"phone_1","value":"p"},{"name":"phone_2","value":"pa"},{"name":"fax","value":"f"},{"name":"email","value":"e"},{"name":"web","value":"w"}]

获得以下结构的最简单方法是:

[{"name": "n", "address_line_1": "a1", "address_line_2": "a2", "town": "t", "postal_code": "p", "region": "r", "phone_1": "p", "phone_2": "pa", "fax": "f", "email":"e", "web": "w"}]

最佳答案

这样的事情应该可行。

let obj = {}
for (let object in array) {
obj[object['name']] = object['value']
}

关于javascript - 创建 JSON 字符串以发布到 jQuery/Javascript 中的网络服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48153279/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com