If you need only json data the you can use getJSON.However both are equivalent as getJSON is short hand for $.ajax.More you can read this :
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.
});
});
In my test.php file:
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();
}
You will receive an object containing :{"answer":"a","score":3,"answer1":"b","score1":5}
if you are working with aspx page then you must use $.ajax as there is an option for content header which must be "application/json" OTHERWISE asp.net will reject the request
Example:
$.ajax({
url: "Demo.aspx/Demo_Method",
contentType: "application/json; charset=UTF-8",
dataType: "JSON",
type: "GET",
success: function (response) {
alert('Success' + response);
}
});
in my aspx page:
[WebMethod()]
[System.Web.Script.Services.ScriptMethod(UseHttpGet = true)]
public static string Demo_Method()
{
return "test";
}
As you mentioned in your Question.Your data seems to be incorrect.Correct Json Format should be like this:
parent: {
child: {
sample: [
{ key: "1", value: "value1" },
{ key: "2", value: "value2" },
{ key: "3", value: "value3" }
]
}
}
If you received a response as in above format then you can simply access this like:
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
});