gpt4 book ai didi

jquery - 如何将表单数据作为单个 JSON 对象发送?

转载 作者:行者123 更新时间:2023-12-03 23:00:28 28 4
gpt4 key购买 nike

下面是我的代码(客户端)通过 JQUERY Ajax 调用以 JSON 格式发送表单数据

$(document).ready(function(){
var contextroot = "/services/"
$("#customerForm").submit(function(e){
e.preventDefault();
var form = $(this);
var action = form.attr("action");
var data = form.serializeArray();

$.ajax({
url: contextroot+action,
dataType: 'json',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(data),
success: function(data){
console.log("DATA POSTED SUCCESSFULLY"+data);
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
});
});

下面是接受 JSON 数据的 SPRING Controller (服务)

@RequestMapping(value="/customer/create", method = RequestMethod.POST)
public CustomerDTO create(@RequestBody CustomerDTO customerDTO) {
return customerService.create(customerDTO);
}

提交表单时,我收到以下错误
HTTP400:错误请求 - 由于语法无效,服务器无法处理该请求。

我猜这个错误是因为表单数据被序列化为 JSON 对象数组,而不是请求正文中的 JSON 对象,如下所示

[{"name":"firstName","value":"John"},{"name":"lastName","value":"Miller"},{"name":"电子邮件","value":"John@gmail.com"},{"name":"mobile","value":"99868377"}]

但是,服务仅接受以下 JSON 数据
<强>{ “名字”:“约翰”, “姓氏”:“米勒”, “电子邮件”:“John.kp@gmail.com”, “手机”:“99868377”}

如何将表单数据转换为单个 JSON 对象,而不是 JSON 对象数组

最佳答案

终于找到解决办法了。我编写了一个生成 JSON 对象的实用方法

$(document).ready(function(){
var contextroot = "/services/"
$("#customerForm").submit(function(e){
e.preventDefault();
var form = $(this);
var action = form.attr("action");
var data = form.serializeArray();

$.ajax({
url: contextroot+action,
dataType: 'json',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(getFormData(data)),
success: function(data){
console.log("DATA POSTED SUCCESSFULLY"+data);
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
});
});

//utility function
function getFormData(data) {
var unindexed_array = data;
var indexed_array = {};

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

return indexed_array;
}

关于jquery - 如何将表单数据作为单个 JSON 对象发送?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40318748/

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