如何从外部文件中检索JSON数据?

I am new to jQuery. I want to access the JSON data which is retrieved from a PHP file.

My PHP code is:

$serverName = "(local)";     
$connectionInfo = array( "Database"=>"sample");    
$conn = sqlsrv_connect( $serverName, $connectionInfo);    
if ($conn) {
     echo "Connection established.<br />";
}
else {
     echo "Connection could not be established.<br />";
     die(print_r(sqlsrv_errors(), true));
}

$str = "Select * from samp2";
$res = sqlsrv_query($conn,$str) or die("Error !");
$response = array();
while($row = sqlsrv_fetch_array($res, SQLSRV_FETCH_ASSOC)) {
    $response['tdata'][] = $row;
}
return json_encode($response);

Output from php file is :

{
    "tdata":[
        { "id": 5, "name": "abi" },
        { "id": 2, "name": "bavi" },
        { "id": 3, "name": "citi" }
    ]
}

My jQuery code is:

$(document).ready(function(e) {
    document.getElementById('a1').innerHTML = "divs";
    $.get('db2.php', function(data) {
        alert("data : " + data);
    }).error(function() {
        alert("Error ! ");
    });
});
<body>
    <div id="a1"></div>
</body>

Output from jQuery is

{
    "tdata": [
        {"id": 5, "name": "abi" },
        {"id": 2, "name": "bavi" },
        {"id": 3, "name": "citi" }
    ]
}

Please tell me how should I access this data.

You can access JSON data when you parse JSON String

Example

$.parseJSON(your_json_string);

This will convert to object

use jQuery.each()

var all_data=data.tdata;

now access inner data

$.each(all_data,function(i,val){
alert(val.id+" "+val.name);
});

Output

5 abi
2 bavi
3 citi

You already have the data in your $.get handler. For example, you can use a mixture of dot and array notation to get information from the first object in the returned array:

$.get('db2.php', function(data) {
    alert(data.tdata[0].name); // = 'abi'

    // alternate
    // alert(data.tdata[0]["name"]); // = 'abi'
})