Jquery json数据不起作用

时间:2014-02-12 14:58:33

标签: jquery json

我有以下代码

$(function(){
  displayRooms();
  editRoom();
});

function displayRooms(){
  $.getJSON("displayData.php", {action: "display"}, function(data){
     $.each(data.roomData, function(i, room){
        $("#display").append("<table><tr><td><a href='#?id=" + room.roomId + "'>Edit</a></td></tr></table>");
     }
  });
}

function editRoom(){
  $("#display a").click(function(){
    var roomid = $(this).attr("href").replace("#?id=","");
    $.getJSON("displayData.php", {action: "edit", roomid: roomid}, function(data){
     $.each(data.roomData, function(i, room){
       $("#roomType").val(room.roomType);
      });
    });
  });

}

我的php文件是正确的,我的sql语句也是正确的,但即使我无法使editRoom函数执行。你能帮帮我吗?

谢谢!

我发布了php函数..

function displayData($dbh, $roomid){
  $data = array();
  $sql = "select roomtype from rooms where roomid = $roomid";
  try{
     $stmt = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
     $stmt->execute();

     while($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT)){
       $data[] = array('roomType' => $row[0]);
     }
     echo '{"roomData":' . json_encode($data) . '}';
      $stmt = null;
  }catch(PDOException $e){
       die($e);
    }
}

2 个答案:

答案 0 :(得分:2)

正在发生的事情是editRoom()在获取JSON数据之前正在运行。您需要做的是在editRoom()的成功回调中加入displayRooms()

答案 1 :(得分:0)

jQuery.getJSON只允许定义成功回调。

使用deferred object尝试这样的事情:

$.getJSON("displayData.php", {action: "display"})
    .done(function(data) {
       $.each(data.rooData, function i, room){
          $("#display").append("<table><tr><td><a href='#?id=" + room.roomId + "'>Edit</a></td></tr></table>");
       }
    })
    .fail(function(jqXHR, textStatus, errorThrown) {
       alert('error');
    })
    .always(function() {
       alert('Error or success');
    });