根据数据库更改页面加载图像

时间:2014-10-23 17:09:10

标签: php ajax json function

一旦我的页面(index.php)加载,就会有一些图像表示座位是否被占用。我很难将图像更改为“已售出”状态。来自'可用'。

数据库有2列: 座位号(例如A1)和状态(例如0) - 如果状态为零,则座位被占用。 我在index.php上找到了我的脚本:

 <script>getSeats();</script>

然后在我的getseats.php中,它返回的数据很好(在URL中测试),所以它返回:

 [{"seatnum":"A1"},{"seatnum":"A2"},{"seatnum":"A3"}] (

以前售出的座位存储在我的数据库中)

我正在努力使用AJAX部件,它会将座椅的图像来源从可用变为售出。代码如下所示,但我不认为大多数是正确的,因为我已经玩了一段时间了。

function getSeats(){
    var myurl="scripts/getseats.php";
    $.ajax({
        type:"GET",
        url: myurl, dataType:'json', // JSON OBJECT
        success: function(taken){

        }
    })// end of success function
    else {

    }

可用的座位文件可用。如果已售出的座位是sold.gif。

如果有人可以花时间帮我ID真的很感激!

简而言之,如果数据库状态为0,我只想让图像从可用状态更改为已售出。

getSeats.php:

<?php
 $noerrors=dbconnect();
 if($noerrors <> 0) {
  echo '{"errorcode":"'.$noerrors.'"}';
 } else {
  $query = "select seatnum from seats where status='0'";
  $link = mysql_query($query);
  if (!$link) {
   echo '{"errorcode":"3"}';
  } else {
   $rows = array();
   while($r = mysql_fetch_assoc($link)) {
    $rows[] = $r;
   }
   $json=json_encode($rows);  
   echo $json;
  }
 }
 function dbconnect(){
  $hostname = "localhost";
  $username = "root";
  $password = "";
  $noerrors = 0;
  $link = @ mysql_connect($hostname, $username, $password);
  if (!$link) {
   $noerrors = 1;
  } else {
   $db_selected = @ mysql_select_db('bookings', $link);
   if (!$db_selected) {
    $noerrors = 2;
   }
  }
  return $noerrors;
 }

?>

HTML:

<td><img id = "A1" src="images/available.gif" style="border:none" onmouseover="over(this)" onmouseout="out(this)" onclick="sold(this.id)" /></td>
     <td><img id = "A2" src="images/available.gif" style="border:none" onmouseover="over(this)" onmouseout="out(this)" onclick="sold(this.id)" /></td>
     <td><img id = "A3" src="images/available.gif" style="border:none" onmouseover="over(this)" onmouseout="out(this)" onclick="sold(this.id)" /></td>

1 个答案:

答案 0 :(得分:1)

你去吧。改变这个:

function getSeats(){
    var myurl="scripts/getseats.php";
    $.ajax({
        type:"GET",
        url: myurl, dataType:'json', // JSON OBJECT
        success: function(taken){

        }
    })// end of success function
    else {

    }

到此:

function getSeats(){
    var myurl="scripts/getseats.php";
    $.ajax({
        type:"GET",
        url: myurl, dataType:'json', // JSON OBJECT
        success: function(taken){
            if (taken) {
                 for (var i=0, l=taken.length; i<l;i++) {
                     $("#" + taken[i].seatnum).attr('src', 'sold.gif'); 
                 }
            }
        }
    });
}

$(document).ready(function() {
    getSeats();
});

这里发生了两件事:

1)Document.ready函数确保在运行脚本之前DOM已准备好与之交互

2)我们遍历getseats.php脚本的响应,并将每个座位的img src设置为seatnum

希望这有帮助!