【发布时间】:2013-07-10 15:28:18
【问题描述】:
我正在创建一个表单数据序列化函数,该函数通过 AJAX 将信息传递到 PHP 文件以进行错误检查和解析。我知道从技术上讲我可以在 JQuery 中使用 .serialize() 方法,但我需要更多地控制我的数据。基本上,我想将表单中的字段解析为多维 Javascript 对象,然后将其转换为 JSON 以通过 AJAX 发送。我已经建立了一种在大多数情况下都有效的方法,但仍然存在一些缺陷。这是我的 Javascript/JQuery 代码:
var formData = { };
function serializeAllFormData() {
$(':input').not('button').each(function() {
//This pulls the fields name for use in error message generation
var fieldName = $(this).parent().children('label').html();
//Takes the value of the field
var value = $(this).val();
//This section finds all fields that needs additional error checking like email/url
var allClasses = $(this).attr('class');
allClasses = allClasses.match(/special_(\w*)/);
if (allClasses != null) {
var special = allClasses[1];
}
else {
var special = '';
}
//Takes the name attribute such as '[contact][email]' and makes an array of just the names. ['contact', 'email']
var locationArray = $(this).attr('name').match(/\w+/g);
//Making a temporary object that will be nested. This object holds all the necessary information for parsing in my errorCheck.php file.
tempObj = { };
tempObj[0] = value;
tempObj[1] = fieldName;
tempObj[2] = $(this).attr('name');
tempObj[3] = special;
//Iterate through, starting with the smallest child of the name attribute and working backwards, nesting the objects
var length = locationArray.length;
for (i = length; i > 0; i--) {
locationName = locationArray[i-1];
if (i > 1) {
var tempObj2 = { };
tempObj2[locationName] = tempObj;
tempObj = tempObj2;
}
//For the last iteration, nest the object in the formData variable itself
if (i == 1) {
formData[locationName] = tempObj;
}
}
});
formData = JSON.stringify(formData);
return formData;
}
因此,如果它只是在一维中运行,它会很好。即名称属性很简单,例如name="[email]" 或name="[phone_number]"。但是,一旦涉及到更复杂的多维字段,formData 对象只会保留最后一个字段。 formData 对象在每次迭代期间都会被覆盖。一个例子是如果我有这个 HTML 结构:
<div><label>Email</label><input type="text" name="[contact][email]" /></div>
<div><label>Phone Number</label><input type="text" name="[contact][phone]" /></div>
如果我运行该方法,一般结构将如下所示:Object (contact => Object (phone => Object (0 => "", 1 => "Phone Number", 2 => "[contact][phone]", 3 => "")))
所以我需要一种方法来确保 formData 中的现有对象不会在每次迭代时被覆盖。
感谢您的帮助!
【问题讨论】:
-
如果我理解正确(根据你的问题的标题)你试图将名称属性表示为一个对象?如果,那为什么不使用
element.getAttributeNode("name");?如果您想要一些自定义类型属性,请使用data-myattr=""ejohn.org/blog/html-5-data-attributes -
我会使用这种方法,但所有
element.getAttributeNode('name');返回的是一个字符串。我需要一个可以转换为 JSON 的对象,以便它在被 PHP 文件解码时可以导航。
标签: javascript object