2008년 4월 3일 목요일

[json] Json 방식으로 Ajax request

먼저 json방식의 자료를 만들어야겠다.

array일 경우
var Beatles = ["Paul","John","George","Ringo"];
var Beatles = new Array("Paul","John","George","Ringo");

Object일 경우
var Beatles = {
     "Country" : "England",
     "YearFormed" : 1959,
     "Style" : "Rock'n'Roll"
}

아래의 경우는 위와 동일함
var Beatles = new Object();
Beatles.Country = "England";
Beatles.YearFormed = 1959;
Beatles.Style = "Rock'n'Roll";

Object 출력
alert(Beatles.Style); //Dot Notation
alert(Beatles["Style"]); //Bracket Notation


Array를 Object에 사용할 경우
var Beatles = {
     "Country" : "England",
     "YearFormed" : 1959,
     "Style" : "Rock'n'Roll",
     "Members" : ["Paul","John","George","Ringo"]
}


Array내부에 Object사용
var Rockbands = [
     {
         "Name" : "Beatles",
         "Country" : "England",
         "YearFormed" : 1959,
         "Style" : "Rock'n'Roll",
         "Members" : ["Paul","John","George","Ringo"]
     }
,
    {
        "Name" : "Rolling Stones",
        "Country" : "England",
        "YearFormed" : 1962,
        "Style" : "Rock'n'Roll",
         "Members" : ["Mick","Keith","Charlie","Bill"]
      }

]

Json Syntax
Javascript Object 와 흡사함

{
"Name" : "Beatles",
"Country" : "England",
"YearFormed" : 1959,
"Style" : "Rock'n'Roll",
"Members" : ["Paul","John","George","Ringo"]
}

내가 원하는것은 만들어진 Json을 어떻게 Ajax를 사용해 전송 할 것인가? 하는 것이다.
그 전에 Json Parser란게 필요하다.
사실 eval( ) 을 사용해서 parsing을 하고 있었는데 parser를 쓰면 더 좋단다. 흠흠..

http://www.json.org/json.js

  • JSON.parse(strJSON) - converts a JSON string into a JavaScript object.
  • JSON.stringify(objJSON) - converts a JavaScript object into a JSON string.
  • 순서는 다음과 같다.
    Client Side
    1. Json을 만든다.
    2. Json파서를 사용해 stringify() 작업을 한다. 이건 object를 string으로 만들어 버리겠다는것?
    3. Send the URL-encoded JSON string to the server as part of the HTTP Request

    Sample:

    var objJSON = {
       "msg" : MSG
      };
      var strJSON = encodeURIComponent(JSON.stringify(objJSON));
      new Ajax.Request("ReceiveJSON.jsp",
       {
        method: "post",
        parameters: "strJSON=" + strJSON,
        onComplete: Respond
       });


    Server Side(php)
    strJSON 파라미터를 받아서 json_decode() 하게 되면 array의 형식으로 변경됨.
    알아서 작업하면 됨....

    -------------------------
    헌데 분명
    Content_Type     => 'application/json',
    Content              => $json_req,
    의 방법을 이용한 경우가 있는데 이럴때는 서버측에서 어떻게 해야 하나?





     



    댓글 없음:

    댓글 쓰기