如何在提交前从表单 serialize() 中获取和替换数据?
How to get and replace data from form serialize() before submitting?
我需要使用 jQuery 提交表单,但在提交之前我想更改其中一个表单字段的值 而不 向用户显示更改.我知道这不是最好的方法,但我的软件要求这样做。
目前我使用:
var submit = $("#submitform").serialize();
序列化数据然后使用
提交它们
$.post('/post', submit)
我的序列化数据是:
entry%5Bbody%5D=hello+and+welcome&addedContexts=presentation&context=prese ntation&selectedContexts=&statementid=×tamp=
我只是想将 entry%5Bbody%5D
的值更改为其他值。
我知道我可以在字符串上使用正则表达式(我找不到哪个?),但也许您知道更优雅的解决方案?比如先序列化表单,再反序列化,改变我需要的值,再序列化?
谢谢!
使用 $("#submitform").serializeArray()
并在数组中搜索 name
属性 等于 "entry[body]"
的项目并编辑其 value
属性.
// convert form data to array
var data = $("#submitform").serializeArray();
// edit data here
// using ES6
data.find(item => item.name === 'entry[body]').value = "something else";
// OR using ES5
data.forEach(function (item) {
if (item.name === 'entry[body]') {
item.value = "something else";
}
});
// then POST
$.post('/post', $.param(data));
我需要使用 jQuery 提交表单,但在提交之前我想更改其中一个表单字段的值 而不 向用户显示更改.我知道这不是最好的方法,但我的软件要求这样做。
目前我使用:
var submit = $("#submitform").serialize();
序列化数据然后使用
提交它们$.post('/post', submit)
我的序列化数据是:
entry%5Bbody%5D=hello+and+welcome&addedContexts=presentation&context=prese ntation&selectedContexts=&statementid=×tamp=
我只是想将 entry%5Bbody%5D
的值更改为其他值。
我知道我可以在字符串上使用正则表达式(我找不到哪个?),但也许您知道更优雅的解决方案?比如先序列化表单,再反序列化,改变我需要的值,再序列化?
谢谢!
使用 $("#submitform").serializeArray()
并在数组中搜索 name
属性 等于 "entry[body]"
的项目并编辑其 value
属性.
// convert form data to array
var data = $("#submitform").serializeArray();
// edit data here
// using ES6
data.find(item => item.name === 'entry[body]').value = "something else";
// OR using ES5
data.forEach(function (item) {
if (item.name === 'entry[body]') {
item.value = "something else";
}
});
// then POST
$.post('/post', $.param(data));