从url解析JSON数据

时间:2013-04-03 07:47:03

标签: ajax json parsing getjson

我有以下格式的JSON数据:

parent: {
       child: {
             sample:[
                     {
                      key:value,
                      key:value,
                     }
                     {
                      key:value,
                      key:value,
                     }
                     {
                      key:value,
                      key:value,
                     }
                    ] 
                 }
            }

我应该如何使用jquery解析这些数据?使用$ ajax或getJSON?哪种方法更好?请帮忙

1 个答案:

答案 0 :(得分:1)

如果你只需要json数据,你可以使用getJSON.However两者都是等价的,因为getJSON是$ .ajax的简写。你可以读到: Difference Between $.getJSON() and $.ajax() in jQuery 在我的剧本中:

$.getJSON('test.php',{ val:"test" }, function (data) {
     $.each(data, function (i, v) {
               //do your work here with each value returned from server side.
     });
});

在我的test.php文件中:

if($_SERVER["REQUEST_METHOD"]=="GET"&&$_REQUEST['val']=="test")
{
    header("Content-type: application/json");
    $a1 = array(  'answer1' => 'a', 'score1'=>3, 'answer2' => 'b', 'score2'=>5);
    echo json_encode($a1);
    die();
}

您将收到一个对象,其中包含:{“answer”:“a”,“score”:3,“answer1”:“b”,“score1”:5}

如果您正在使用aspx页面,则必须使用$ .ajax,因为内容标题有一个选项,必须是“application / json”OTHERWISE asp.net将拒绝该请求

示例:

        $.ajax({
            url: "Demo.aspx/Demo_Method",
            contentType: "application/json; charset=UTF-8",
            dataType: "JSON",
            type: "GET",
            success: function (response) {
                alert('Success' + response);
            }
        });

在我的aspx页面中:

    [WebMethod()]
    [System.Web.Script.Services.ScriptMethod(UseHttpGet = true)] 
    public static string Demo_Method()
    {
        return "test";
    }

正如您在问题中提到的那样。您的数据似乎不正确。错误的Json格式应该是这样的:

 parent: { 
     child: { 
          sample: [
                   { key: "1", value: "value1" }, 
                   { key: "2", value: "value2" }, 
                   { key: "3", value: "value3" }
                  ]
            }
         } 

如果您收到上述格式的回复,则只需访问以下内容即可:

 var response= { parent: { child: { sample: [{ key: "1", value: "value1" }, { key: "2", value: "value2" }, { key: 3, value: "value3"}]}} };

 var samples_arr=response.parent.child.sample;  //create a sample Array.


 $.each(samples_arr,function(){
      alert(v.key+" and "+ v.value); // access here your each element
 });