我的目标是用我的表单数据构造一个对象
。
经过一番谷歌搜索后,人们建议我使用 serialize()
现在,我从表单数据中得到了这个
_method=PUT&_token=rs8iLxwoJHSCj3Cc47jaP5gp8pO5lhGghF1WeDJQ&max_down=256&max_up=256&cpe_mac=000D6766F2F6&device_mac=503275AE7A69
有没有办法将长字符串转换为对象?
还有其他方法可以达到这个目的吗?
这方面的任何指示对我来说都意义重大!
<小时/>我已经尝试过
$( "form#editRateLimitForm" ).on( "submit", function( event ) {
event.preventDefault();
var serialize = $( this ).serialize() ; // Nothing printing out
console.log(serialize); // _method=PUT&_token=rs8iLxwoJHSCj3Cc47jaP5gp8pO5lhGghF1WeDJQ&max_down=256&max_up=256&cpe_mac=000D6766F2F6&device_mac=503275AE7A69
});
最佳答案
我已经多次使用这种方法。
$("form#editRateLimitForm").on("submit", function( event ) {
event.preventDefault();
var formObj = {},
formData = $(this).serializeArray(),
i;
for (i in formData) {
formObj [formData[i]['name']] = formData[i]['value'];
}
console.log(formObj);
});
console.log 应显示
{_method: 'PUT', token:'rs8iLxwoJHSCj3Cc47jaP5gp8pO5lhGghF1WeDJQ', max_down: '256',
max_up: '256', cpe_mac: '000D6766F2F6', device_mac: '503275AE7A69'}
关于javascript - 获取表单数据作为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34298848/