0

I have a problem with getJSON. Following is the scenario -

Here is my HTML code -

  <h3 align="center"> Example 1</h3>
  <table align="center">
    <tr>
      <td><select name="stud_sel" onChange="getDetails(this)">
          <option value="100">Lohith</option>
          <option value="101">Ranjeet</option>
          <option value="102">Karthik</option>
          <option value="103">Pav</option>
        </select></td>
    </tr>
  </table>
  <br/>

  <!--HERE WRITE THE RESPONSE DATA -->
  <div id ="stud_tbl"  align="center"> </div>
  <!---END-->

Here is my Javascript function ---->

function getDetails(id) {
var myTable = '' ;
myTable += '<table id="myTable" cellspacing=0 cellpadding=2 border=1>' ;
var id_val = id.value;
//window.alert(id_val);
var url = "http://localhost:81/json-with-jquery/json.php?id="+id_val; 
alert (url);
$.getJSON(url, function(json) {
                $.each(json, function(i,v) {                
                  myTable +=   "<tr><td>"+i+"</td><td>"+v+"</td></tr></table>";               
                });
                $("#stud_tb1").html(myTable) ;

        });
};

And the PHP file from where data is coming to my JS function is -

 <?php
    include 'configure.php';
    $stud_id = $_GET['id'];
    echo $_GET['id'];
    $qr = "SELECT * FROM student_details WHERE regno = $stud_id";
    $res= mysql_query($qr);
    $row = mysql_fetch_array($res);

    $stud_arr["full_name"] = $row["full_name"];

$stud_arr["reg_no"] = $row["regno"];
$stud_arr["address"] = $row["address"];
$stud_arr["mark1"] = $row["mark1"];
$stud_arr["mark2"]= $row["mark2"];
$stud_arr["mark3"] = $row["mark3"];
 header('Content-type: application/json');
  echo json_encode($stud_arr);    
?>

The problem here is when I run my PHP file individually, it's giving me the expected data in JSON format, with the help of json_encode($stud_array). The same when I am trying to display on my HTML page, I don't receive any data on the page.

The "alert(url)" in my JS function is properly alerting message as "http://localhost:81/json-with-jquery/json.php?id=102" when I selected the list item with ID 102.

Am not sure why the data is not being displayed. I hope I have the Javascript written properly. Please help.

4

2 回答 2

1

您的输出不是有效的 json,这是问题所在,您echo $_GET['id'];正在破坏您的 json 输出,请将其删除。如果您想在输出中发送它,请将其放入 json 响应中。

$stud_arr["id"] = $_GET['id'];
header('Content-type: application/json');
echo json_encode($stud_arr);   
于 2013-04-29T06:33:37.687 回答
1

正确填充您的表格,

myTable="<table>";
$.each(json, function(i,v) {                
                  myTable +=   "<tr><td>"+i+"</td><td>"+v+"</td></tr>";               
                });
myTable+="</table>";
于 2013-04-29T06:32:01.123 回答