오류 검사 및 구문 분석을 위해 AJAX를 통해 PHP 파일로 정보를 전달하는 양식 데이터 직렬화 함수를 만듭니다. 기술적으로 JQuery에서 .serialize()
메서드를 사용할 수는 있지만 데이터를 더 많이 제어해야한다는 것을 알고 있습니다. 기본적으로 나는 AJAX를 통해 JSON으로 변환 된 다차원 Javascript 객체로 내 양식의 필드를 구문 분석하려고합니다. 나는 대부분의 경우 작동하지만 여전히 결함이있는 메소드를 구축했습니다. 내 자바/JQuery 코드는 다음과 같습니다.HTML 이름 속성을 자바 스크립트 객체로 변환
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 객체를 덮어 씁니다. 나는이 방법을 실행하면
<div><label>Email</label><input type="text" name="[contact][email]" /></div>
<div><label>Phone Number</label><input type="text" name="[contact][phone]" /></div>
는, 일반적인 구조는 다음과 같이 보일 것이다 :이 HTML 구조가있는 경우를 예로들 수 Object (contact => Object (phone => Object (0 => "", 1 => "Phone Number", 2 => "[contact][phone]", 3 => "")))
그래서 내가 확인하는 방법이 필요를 그 안에 존재하는 객체 formData는 각 반복에서 덮어 쓰지 않습니다.
도움 주셔서 감사합니다.
만약 당신이 정확하게 (당신의 질문의 제목을 기반으로) 당신이 객체로서 이름 속성을 나타내려고 노력 했습니까? 그렇다면'element.getAttributeNode ("name");'을 사용하지 않는 이유는 무엇입니까? 'data-myattr = ""'http://ejohn.org/blog/html-5-data-attributes/ – Givi
을 사용하려면 사용자 정의 유형 속성을 사용하려면이 방법을 사용하지만 모든 'element.getAttributeNode (' name ');'returns는 문자열입니다. JSON으로 변환 할 수있는 객체가 필요하므로 PHP 파일에 의해 디코딩 될 때 탐색 할 수 있습니다. – MrGrinst