1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="utf-8">
    <script src="js/jquery.js"></script>
</head>
<body>
    <form name="frm" method="post" action="">
        <input type="text" name="a" value="1">
        <input type="text" name="b" value="2">
        <input type="hidden" name="c" value="3">
        <textarea name="d" rows="8" cols="40">4</textarea>
        <select name="e">
            <option value="5" selected="selected">5</option>
            <option value="6">6</option>
            <option value="7">7</option>
        </select>
        <input type="checkbox" name="f" value="8">
        <button type="submit">전송</button>
    </form>
 
    <script>
 
        var obj = { width:1680, height:1050 };
        var data1 = $.param( obj ); // 자바스크립트 객체(리터럴)을 쿼리스트링으로 만들어준다.      
        console.log(data1)          // 결과 : width=1680&height=1050
 
 
        var data2 = $("form").serialize();  // form의 입력데이터를 쿼리스트링으로 만들어준다.
        console.log(data2);               // 결과 : a=1&b=2&c=3&d=4&e=5 
 
 
        var data3 = $('form').serializeArray(); // form의 입력데이터를 배열의 Object형태로 만들어준다.
        console.log(data3);
        /*
        
        결과 :  
        [Object, Object, Object, Object, Object]
            0: Object name: "a"value: "1"
            1: Object name: "b"value: "2"
            2: Object name: "c"value: "3"
            3: Object name: "d"value: "4"
            4: Object name: "e"value: "5"
            length: 5
        */
 
//--------------------------------------------------------------------------------------------------------------------------------
 
        // JSON.stringify 와 JSON.parse는 jQuery 메서드는 아니지만 유용하게 쓰인다. 참고...
 
       var json_str = JSON.stringify(data3); // Obejct(리터럴)을 json문법에 맞게 string 타입으로 변형
       console.log(json_str)  
       //결과 : '[{"name":"a","value":"1"},{"name":"b","value":"2"},{"name":"c","value":"3"},{"name":"d","value":"4"},{"name":"e","value":"5"}]' //string
 
 
       var json_obj = JSON.parse(json_str); // json문법의 string을 배열의 Object형태로 변형
       console.log(json_obj)                // 결과는 data3과 같다.    //object
 
//--------------------------------------------------------------------------------------------------------------------------------
 
    var data = '{"a":"100", "b":"200" }';
 
    //JSON.parse //JSON.stringify 함수는 두번째 파라미터로 함수(key, value)를 받을 수 있고 filter기능을 한다.
    var result = JSON.parse(data, function(key, value){
 
        return key === 'a' ? 9999 : value; 
        
    });
    console.log(result)  // Object {a: 9999, b: "200"}
 
    </script>    
</body>
</html>


반응형
Posted by 힘없는염소