使用Ajax Call检索数据时出错

时间:2013-04-29 06:27:17

标签: php javascript html ajax

我遇到getJSON问题。以下是方案 -

这是我的HTML代码 -

  <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-->

这是我的Javascript函数----&gt;

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) ;

        });
};

数据来自我的JS函数的PHP文件是 -

 <?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);    
?>

这里的问题是当我单独运行我的PHP文件时,它在json_encode($ stud_array)的帮助下以JSON格式给出了预期的数据。 当我试图在我的HTML页面上显示时,我没有在页面上收到任何数据。

当我选择ID为102的列表项时,我的JS函数中的“alert(url)”正确地将消息警告为“http://localhost:81/json-with-jquery/json.php?id=102”。

我不确定为什么没有显示数据。我希望我能正确编写Javascript。请帮忙。

2 个答案:

答案 0 :(得分:1)

正确填充表格,

myTable="<table>";
$.each(json, function(i,v) {                
                  myTable +=   "<tr><td>"+i+"</td><td>"+v+"</td></tr>";               
                });
myTable+="</table>";

答案 1 :(得分:1)

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

$stud_arr["id"] = $_GET['id'];
header('Content-type: application/json');
echo json_encode($stud_arr);   
相关问题