gpt4 book ai didi

java - 在表单提交上发送 json 对象

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:33:51 25 4
gpt4 key购买 nike

我有一个通常的形式。我唯一尝试不同的是将 3 个输入值分组到一个 json 中。当我点击提交时,我想像往常一样发送其他输入,但那些 3 作为一个 json。我已经使用 jquery 将它变成了 json,但无法理解如何在提交点击时发送它。请查看我的代码,让我知道缺少什么。 (仅供引用,我正在研究 spring mvc)我有这个表格:

    <form class="form-horizontal" action="success" method="post" role="form">
<div class="form-group">
<input type="text" name="name" id="name" class="form-control" placeholder="Name" value="">
<input type="text" name="dob" id="dob" class="form-control" placeholder="Date of Birth" value="">
</div>

<div class="row form-group">
<div class="col-sm-3">
<input type="text" id="school_name" class="form-control" placeholder="school/college name" />
</div>
<div class="col-sm-3">
<select class="form-control year" id="year">
<option>1</option>
<option>2</option>
</select>
</div>
<div class="col-sm-3">
<input type="text" class="form-control" id="qualification" placeholder="qualification" />
</div>
<div class="col-sm-3">
<button type="button" class="btn btn-primary" id="add" value="add">Add More</button>
</div>
</div>

<input type="submit" class="btn btn-danger form-control" id="save" value="Save">
</form>

我的 jquery 代码是:

        $(document).on('click',"#save",function() {
var $items = $('#school_name, #year,#qualification ')
var education=null;
var json = {}
$items.each(function() {
json[this.id] = $(this).val();
});
education= JSON.stringify(json);
alert(education) //this gives me the required result
window.location="success?education="+education;
// I guess something is wrong here
});

最佳答案

不清楚服务器需要什么类型的数据。因为,如果服务器接受 JSON 格式的数据,则根本无法使用查询参数发送数据。

你可能想看看 $.ajax .您可以使用 data 键将对象 json 直接发送到服务器,如下所示:

$.ajax({
url: 'success',
data: json
})
.then(function(response) {
// Handle the response here
});

它会简单地使用查询参数将数据发送到 url 键指定的服务器 URL。如果您的服务器改为接受 JSON 格式的数据,您可能需要将请求方法更改为 POST 并将 contentType 设置为 json,如下所示:

$.ajax({
method: 'POST',
url: 'success',
contentType: 'application/json',
data: json
})
.then(function(response) {
// Handle the response here
});

希望这能澄清您的问题。有关详细信息,请查看浏览器开发人员工具的网络选项卡,了解数据是如何提交到服务器的。

关于java - 在表单提交上发送 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47547507/

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