gpt4 book ai didi

javascript - 将 HTML 名称属性转换为 Javascript 对象

转载 作者:行者123 更新时间:2023-11-28 09:02:20 26 4
gpt4 key购买 nike

我正在创建一个表单数据序列化函数,该函数通过 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 属性很简单,例如 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 => "[联系人][电话]", 3 => "")))

所以我需要一种方法来确保 formData 中的现有对象不会在每次迭代时被覆盖。

感谢您的帮助!

最佳答案

尝试正确初始化临时变量。例如:

var tempObj = [];

现在您实际上正在创建全局变量,这些变量在每次迭代中都可以重用。

关于javascript - 将 HTML 名称属性转换为 Javascript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17574764/

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