0

我有以下格式的 JSON 数据:

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

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

4

1 回答 1

1

如果您只需要 json 数据,您可以使用 getJSON。但是两者都是等效的,因为 getJSON 是 $.ajax.More 的简写,您可以阅读: Difference between $.getJSON() and $.ajax() in jQuery In my script :

$.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”否则 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
 });
于 2013-04-03T07:53:40.963 回答