我正在尝试创建一个数组并获取表单提交的所有值并将它们放入该数组中。我需要这样做,因为在这段代码的 .each 函数中,我必须对每个客户端的所有值进行额外的加密。这是一个包含数百个正在更改的字段的表单。所以它必须是一个数组才能工作。我尝试在 jQuery 中执行以下操作和其他几种类似的操作,但没有成功。谁能帮忙?谢谢。
编辑:发布了我的工作解决方案。谢谢您的帮助。 编辑 2:接受 sabithpocker 的回答,因为它允许我保留我的 key 名称。
最佳答案
var inputArray = {};
//jQuery(this).serializeArray() = [{name: "field1", value:"val1"}, {name:field2...}...]
jQuery(this).serializeArray().each(function(index, value) {
inputArray[value.name] = encrypt(value.value);
});
//now inputArray = [{name: "field1", value:"ENCRYPTED_val1"}, {name:field2...}...]
//now to form the POST message
postMessages = [];
$(inputArray).each(function(i,v){
postMessages.push(v.name + "=" + v.value);
});
postMessage = postMessages.join('&');
查克 serializeArray()查看 JSON 数组格式。
很明显,问题是您的情况下的 this
不是您假设的数组。请说明 this
指针指的是什么,或者通过执行 console.log(this)
当你更新你的答案时,在你的例子中 this
指针指的是你提交的表单,你想如何迭代表单?你想用每个实现什么?
更新
使用大写而不是加密来摆弄
$('#x').submit(function (e) {
e.preventDefault();
var inputArray = [];
console.log(jQuery(this).serializeArray());
jQuery(jQuery(this).serializeArray()).each(function (index, value) {
item = {};
item[value.name] = value.value.toUpperCase();
inputArray[index] = item;
});
console.log(inputArray);
postMessages = [];
$(inputArray).each(function (i, v) {
for(var k in v)
postMessages[i] = k + "=" + v[k];
console.log(i, v);
});
postMessage = postMessages.join('&');
console.log(postMessage);
return false;
});
关于javascript - 为什么 jQuery 不能在 ajax post 之前更新数组数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17644615/