2010-08-05 4 views
1

구조화 된 양식을 기반으로 복잡한 JavaScript 객체로 양식을 변환하는 방법이 있습니까? 이것은 더 나은 방법으로 수행 할 필요가있는 경우html 양식을 복잡한 JavaScript 객체로 변환하는 방법

는 지금, 나는 아무 생각이 없지만, 기본적으로 내가 이런 걸 원하는 :

<form> 
    <input name="Foo" value="1" /> 
    <input name="Parent.Child1" value="1" /> 
    <input name="Parent.Child2" value="2" /> 
</form> 

을 나는 자바 스크립트이 원하는 :

var form = GetForm(); 
var obj = ConvertFormToComplexObject(form); 

// 
// Followings should be true 
// 
// obj.Foo == 1; 
// obj.Parent != null 
// obj.Parent.Child1 == 1; 
// obj.Parent.Child2 == 2; 
// 

하나를 제안?

감사합니다,

+1

어떤 목적을 위해? 이것은 기본 DOM 스크립팅의 변형처럼 보입니다. 왜 일반 DOM 스크립팅을 사용하는 법을 배워야합니까? –

+0

흠 .. 기본적으로 동적 양식 요소가있는 양식이 있습니다. 사용자는 각각의 "객체"가 각각 정수와 문자열을 포함하는 "객체"목록을 추가 할 수 있습니다. name = "1_Integer"또는 name = "2_String"과 같은 명명 규칙을 사용하여 양식을 플랫하게 유지할 수 있지만 파서를 작성해야합니다. JavaScript 개체를 올바르게 작성해야합니다. Json을 사용하여 직렬화하고 Json이 복잡성을 처리하도록 할 수 있습니다. –

답변

2

난 그냥 그렇게 플러그인을 썼다. 누군가가 도움이되기를 바랍니다. 버그를 발견하면 알려주세요.

다음은 serializeObject의 코드입니다.JS :

여기
$.fn.serializeObject = function() { 
    var o = {}; 
    var a = this.serializeArray(); 
    $.each(a, function() { 

     var arrayIndex = function(name) { 
      //note: 2d array not handled 

      var startIndex = name.indexOf('['); 
      var endIndex = name.indexOf(']'); 

      if (startIndex == -1 || endIndex == -1 || endIndex != name.length - 1) 
       return null; 

      return name.substr(startIndex + 1, endIndex - startIndex - 1); 
     } 

     var trimArrayIndex = function(name) { 
      var startIndex = name.indexOf('['); 
      return name.substr(0, startIndex); 
     } 

     var createObject = function(obj, className, value) { 
      if (className.length == 0) 
       return; 

      var classNames = className.split("."); 

      if (classNames.length == 1) { 

       if (obj[classNames[0]] == null) { 
        obj[classNames[0]] = value; 
       } 
       else if (obj[classNames[0]] instanceof Array) { 
        obj[classNames[0]].push(value); 
       } 
       else { 
        var temp = obj[classNames[0]]; 

        obj[classNames[0]] = new Array(); 
        obj[classNames[0]].push(temp); 
        obj[classNames[0]].push(value); 
       } 

       return; 
      } 

      var index = arrayIndex(classNames[0]); 
      var isArray = index != null; 

      if (!isArray) { 
       if (obj[classNames[0]] == null) { 
        obj[classNames[0]] = new Object(); 
       } 

       createObject(obj[classNames[0]], className.substr(classNames[0].length + 1), value); 
      } 
      else { 
       var aryName = trimArrayIndex(classNames[0]); 

       if (obj[aryName] == null) { 
        obj[aryName] = new Array(); 
       } 
       else if (!obj[aryName] instanceof Array) { 
        throw "unable to serialize " + aryName + " as an array"; 
       } 

       var ary = obj[aryName]; 
       var nextObj; 

       if (ary[parseInt(index)] == null) { 
        ary[parseInt(index)] = new Object(); 
       } 

       nextObj = ary[parseInt(index)]; 

       createObject(nextObj, className.substr(classNames[0].length + 1), value); 
      } 
     } 

     createObject(o, this.name, this.value || ''); 
    }); 
    return o; 
}; 

$.fn.replaceStarWithIndex = function() { 
    var a = this.serializeArray(); 
    var form = this; 


    var arrayIndex = function(name) { 
     var startIndex = name.indexOf('['); 
     var endIndex = name.indexOf(']'); 

     if (startIndex == -1 || endIndex == -1) { 
      return null; 
     } 

     return name.substr(startIndex + 1, endIndex - startIndex - 1); 
    } 

    var trimArrayIndex = function(name) { 
     var startIndex = name.indexOf('['); 
     return name.substr(0, startIndex); 
    } 

    for (var key in a) { 
     var index = arrayIndex(a[key].name); 

     if (index == null || index != "*") { 
      continue; 
     } 

     var count = 0; 
     var trimName = trimArrayIndex(a[key].name); 

     while (true) { 
      var elementName = a[key].name.replace('*', count); 
      var element = form[0][elementName]; 

      if (element == null) { 
       $(form[0][a[key].name]).first().attr('name', elementName); 
       break; 
      } 
      count++; 
     } 
    } 
} 

테스트입니다 :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" > 
<head> 
    <title>Test</title> 
    <link rel="stylesheet" href="http://github.com/jquery/qunit/raw/master/qunit/qunit.css" type="text/css" media="screen" /> 

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" ></script> 
    <script type="text/javascript" src="http://github.com/jquery/qunit/raw/master/qunit/qunit.js" ></script> 
    <script type="text/javascript" src="serializeObject.js" ></script> 
</head> 

<body> 

<h1 id="qunit-header">Test serializeObject</h1> 
<h2 id="qunit-banner"></h2> 
<h2 id="qunit-userAgent"></h2> 
<ol id="qunit-tests"></ol> 

<!--Test Form --> 

<form id="form1" style="display:none;"> 
    <input type="text" name="Parent.Child1" value="child1"/> 

    <input type="text" name="Parent.Child2" value="child2a"/> 
    <input type="text" name="Parent.Child2" value="child2b"/> 

    <input type="text" name="Parent.Child3" value="3"/> 
    <input type="text" name="Parent.Child3" value="2"/> 
    <input type="text" name="Parent.Child3" value="1"/> 

    <input type="text" name="Parent.Child4[0].Child1" value="11" /> 
    <input type="text" name="Parent.Child4[0].Child2" value="aa" /> 

    <input type="text" name="Parent.Child4[1].Child1" value="22" /> 
    <input type="text" name="Parent.Child4[1].Child2" value="bb" /> 



</form> 

<form id="form2" style="display:none;"> 
    <input type="text" name="Child1[0].Child1" value="0" /> 
    <input type="text" name="Child1[*].Child1" value="1" /> 
    <input type="text" name="Child1[*].Child1" value="2" /> 

    <input type="text" name="Child2[2]" value="2" /> 
    <input type="text" name="Child2[*]" value="0" /> 
    <input type="text" name="Child2[*]" value="1" /> 
</form> 

<script type="text/javascript"> 
    $(document).ready(function() { 
     var obj = $('#form1').serializeObject(); 

     test("Parent should exist", function() { 
      equals(true, obj.Parent != null); 
     }); 

     test("Child1 should exist within parent", function() { 
      equals(true, obj.Parent.Child1 != null); 
     }); 

     test("Should create array for items with same name", function() { 
      equals("child2a", obj.Parent.Child2[0]); 
      equals("child2b", obj.Parent.Child2[1]); 
      equals("3", obj.Parent.Child3[0]); 
      equals("2", obj.Parent.Child3[1]); 
      equals("1", obj.Parent.Child3[2]); 
     }); 


     test("Should allow array of objects", function() { 
      equals("11", obj.Parent.Child4[0].Child1); 
      equals("aa", obj.Parent.Child4[0].Child2); 
      equals("22", obj.Parent.Child4[1].Child1); 
      equals("bb", obj.Parent.Child4[1].Child2); 
     }); 

     $('#form2').replaceStarWithIndex(); 

     test("Should replace * with index", function() { 
      equals("0", $('#form2 input[name="Child1[0].Child1"]').val()); 
      equals("1", $('#form2 input[name="Child1[1].Child1"]').val()); 
      equals("2", $('#form2 input[name="Child1[2].Child1"]').val()); 

      equals("0", $('#form2 input[name="Child2[0]"]').val()); 
      equals("1", $('#form2 input[name="Child2[1]"]').val()); 
      equals("2", $('#form2 input[name="Child2[2]"]').val()); 
     }); 

    }); 
</script> 

</body> 
</html> 
0

는 난 당신이하는 경우 - document.forms을 요구하고 추측 [0]

뭔가 같은 :

VAR 양식 = 예 : document.forms [0]; // 또는 시도로

은 다음의 값에 액세스 할 수 있습니다 ... document.getElementByName 될 수 있습니다 form.Foo를 = 1

당신이 DOM 자체에 대한하면 충분 복잡한 객체로 변환 할 필요가 없습니다

0
var form = document.forms[0]; 

돌려 HTML 요소 개체, 당신은 HTML 요소도

를 얻을

form.Foo 

을 사용할 수 있습니다

하지만 값을 얻으려면, 사용해야합니다

form.Foo.value 

또는

form['Parent.Child1'].value; 

DEMO

P.S.를 볼 수 있습니다 나는 ConvertFormToComplexObject() 메소드가 좋지 않다고 생각한다. 당신은 그것을 만들 필요가 없다.

+0

Zenofo에게 감사의 말을 전합니다. 그러나 "Parent"를 객체로 사용하여 원하는 경우 Json으로 직렬화하는 옵션을 가질 수 있습니다. 귀하의 경우 form.Parent null 또는 form.Parent.Child1 오류를 제공 –

0

매우 기본적인 버전이지만 이름이 어떻게 작동하는지 기본적인 이해를 제공합니다.

$(function(){ 
    var elements = document.forms[0].elements, 
     foo = {}; 
    for(var i=0; i<elements.length; i++) { 
     var element = elements[i]; 
     var names = element.name.split('.'); 
     if(names.length >1) { 
      foo[names[0]] = foo[names[0]] || {}; 
      foo[names[0]][names[1]] = element.value; 
     } else { 
     foo[names[0]] = element.value; 
     } 

    } 
    console.log(foo) 
});​ 
0

수많은 자바 스크립트 라이브러리에이 기능이 있습니다. 구현을 사용하거나 적어도 어떻게 수행했는지 볼 것을 제안합니다.

프로토 타입 : http://www.prototypejs.org/api/form/serialize

사용법 : $('id-of-form').serialize(true)

+0

jQuery 하나 살펴 봤지만 "구조화 된"개체 직렬화를 수행하지 않습니다. 사실,이 객체를 객체로 직렬화하지도 않습니다. 가장 가까운 번호 : http://stackoverflow.com/questions/1184624/serialize-form-to-json-with-jquery –

관련 문제