gpt4 book ai didi

javascript - JavaScript 新手 : how to avoid sending data that have not changed?

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

我是一个 Javascript 学习新手,我想发布输入复选框的序列化数据。数据被发送到服务器以更新SQL表中的相应字段。稍后,用户可以查看他第一次所做的选择并取消选择一些复选框。如果我理解得很好,只会发送选定的项目,而不发送未选定的项目。如何发送更新新选择的项目和新未选择的项目所需的所有信息?

我发现的唯一解决方案是进行两次更新:第一次将所有行重置为 0,第二次将序列化数组中发送的所选项目(新选择或未选择)设置为 1。有没有更优化的方法来完成这项工作?理想情况下,我只会更新已更改的数据。可能吗?

问候,帕特里克

最佳答案

如果我理解正确,您可以过滤复选框,然后也可以将未选中的框添加到参数中。

我在 SO 找到了相关代码。请参阅this question .

下面的演示和这里的 jsfiddle仅当用户更改数据时才会执行 ajax post。不确定这是否是您想要的。

(SO 的演示稍作修改,因为需要 JSONP 才能避免 CORS 错误。)

var data = "";

$('form').submit(function (evt) {
evt.preventDefault();
//console.log($(this).serialize());
var formData = $(this).serialize();

// source from this SO question https://stackoverflow.com/questions/10147149/how-can-i-override-jquerys-serialize-to-include-unchecked-checkboxes
// include unchecked checkboxes. use filter to only include unchecked boxes.
$.each($('form input[type=checkbox]')
.filter(function (idx) {
return $(this).prop('checked') === false
}),

function (idx, el) {
// attach matched element names to the formData with a chosen value.
var emptyVal = "off";
formData += '&' + $(el).attr('name') + '=' + emptyVal;
});

console.log(formData);
if ( data != formData ) { // check if user changed the data.
$.ajax({
url: 'http://jsfiddle.net/echo/jsonp/',
type: 'POST',
//data: formData, // this will work but for jsfiddle echo the code below is required.
dataType: "jsonp",
data: {
json: JSON.stringify({
serialized: formData
}),
delay: 1
},
success: function(res) {
console.log('posted: ', res);
}
});
}

data = formData;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<label for="first">check1</label>
<input name="first" id="first" type="checkbox" />
<label for="second">check2</label>
<input name="second" id="second" type="checkbox" />
<label for="third">check3</label>
<input name="third" id="third" type="checkbox" />
<label for="fourth">check4</label>
<input name="fourth" id="fourth" type="checkbox" />
<input type="submit" value="update" />
</form>

关于javascript - JavaScript 新手 : how to avoid sending data that have not changed?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29322249/

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