【问题标题】:submit form with additional options?提交带有其他选项的表格?
【发布时间】:2019-01-24 05:00:29
【问题描述】:
例如,我有一个页面可以编辑用户数据。页面顶部是决定是否来自它自己的提交。如果提交则保存数据并关闭页面。如果不是,则输入字段可见。
但我希望能够在某些数据发生更改时重新加载页面(例如下拉菜单的机会)。因为当这个下拉菜单被更改时,其他数据应该被更改或禁用等。因此我需要用它的 POST 数据重新加载页面,但不保存数据。但是当我使用 submit() 时,它将被保存并关闭。
有没有办法用 POST 数据发送表单,但能够决定是最终保存数据还是只用 POST 数据更新表单?
谢谢!
马库斯
【问题讨论】:
标签:
javascript
forms
post
submit
reload
【解决方案1】:
A page reload isn't the best user experience when an options changes and you need to hide or show details on the page.如果可以的话,我建议将该逻辑完全放在前端。如果您需要基于仅存在于服务器上的答案的其他数据,请使用对后端的 GET 调用并使用结果填充前端。
没有更多细节,我只能创建这个小 sn-p 来让您了解如何做到这一点。注释在代码中。
$('document').ready(function() {
$('#state').change(function() {
// NOTE: code only used to show a visual change. Add logic into the .get call success function. Here, read the state and set the input to enabled or disabled depending on what is returned from the server.
var state = this.value;
$("#name").prop('disabled', state === "0" ? 'disabled' : '');
// Make the server call, use GET as you are getting information.
// The variable provided to the backend is state with value 0 or 1, (?state=0)
$.get("https://yourserver/?state=" + state, function(data) {
// when the call is successful, use the data object to determine what should be done.
var state = data.state;
$("#name").prop('disabled', state === "0" ? 'disabled' : '');
});
});
});
input:disabled {
background-color: #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<select id="state">
<option value="1">Enabled</option>
<option value="0">Disabled</option>
</select>
<p><input type="text" id="name" placeholder="Your name"></p>
<div class="result"></div>
</form>