2012-09-17 39 views
2

我搜索了高和低,看看这是否可能,并提出空手。首先,这里是我的代码:PHP数据库显示在不同定位标签的相同字段中

<div id="information" style="display:none"> 
</div> 

<?php $seat = mysql_query("SELECT * FROM people WHERE seat='C3-24'"); $row = mysql_fetch_array($seat); ?> 

    <ul> 
     <li> <?= $row['first_name']; ?></li> 
     <li> <?= $row['last_name']?> </li>   
     <li> <?= $row['seat']?></li>    
    </ul>     

</div><!-- information --> 

<div id="c3-24" class="seat"> 
    <a class="trigger" onClick="document.getElementById('information').style.display='block';"></a></div> 
</div> 

基本上我想,当我选择div id "c3-25"更新li列表。现在我知道有WHERE seat="C3-25"将只输出数据库的行,但我想重复使用此结构与其他位置。从我读到的这是不可能的。理想情况下,我想要列出div(c3-24至c3-50),并在li字段中单击锚标签时显示相应的信息。

我试过把多个“信息”divs,但信息最终堆叠在另一个之上。

任何帮助,将不胜感激。

+2

请不要使用'mysql_ *'函数来编写新代码。他们不再维护,社区已经开始[弃用程序](http://goo.gl/KJveJ)。请参阅* [红盒子](http://goo.gl/GPmFd)*?相反,您应该了解[准备好的语句](http://goo.gl/vn8zQ)并使用[PDO](http://php.net/pdo)或[MySQLi](http://php.net/ mysqli的)。如果你不能决定哪些,[这篇文章](http://goo.gl/3gqF9)会帮助你。如果你选择PDO,[这里是很好的教程](http://goo.gl/vFWnC)。 –

回答

1

问题在于时机。有两个非常独立的执行上下文值得考虑,以了解您的问题:

  1. 页面构建(PHP) - Web服务器创建HTML发送到浏览器;
  2. 用户交互(JavaScript) - 用户的浏览器已呈现该页面,并且用户正在与其进行交互。

由于页面构建时间发生在浏览器获取信息之前,它不可能实现用户决定(稍后会发生)。

这种解决方案的典型解决方案是将应用程序分解为多个请求。作为最佳做法,最好将您的JavaScript分成单独的文件,并使用称为委派的技术来减少代码量。

下面是我该怎么做。首先,发下来的页面结构(PHP/HTML):

<div id="information"> 
    <!-- leave empty --> 
</div> 
<div class="seats"> 
    <div class="seat"> 
    <a class="trigger">c3-24</a></div> 
    </div> 
    <div class="seat"> 
    <a class="trigger">c3-25</a></div> 
    </div> 
    ... 
</div> 

然后设置在单独的JavaScript文件中的用户交互:

// setup a click handler on the parent 'seats' div 
document.querySelector('.seats').addEventListener('click', function(e){ 
    // check if the target of the click was actually an anchor tag with class=target 
    if (e.target.classList.contains('target')) { 
    var 
     // use the text of the anchor tag to get the seat 
     seat = e.target.textContent, 
     // create an XMLHttpRequest to asynchronously get the seat details 
     req = new XMLHttpRequest(); 
    // handle server result by inserting details 
    req.onreadystatechange = function() { 
     if(req.readyState === 4){ 
     document.getElementById('information').innerHTML = req.responseText; 
     } 
    }; 
    req.open("GET", "seatdata.php?seat=" + encodeURIComponent(seat), true); 
    req.send(null); 
    } 
}); 

最后,实现一个单独的PHP脚本获取数据为特定的座位(例如seatdata.php)。您的脚本应通过$_GET['seat']获取seat网址参数并在查询中使用该参数。

根据Madara的评论,请勿直接使用mysql_query函数,因为它已被弃用,请改用更好的东西。

+0

嘿,谢谢你的帮助。我很欣赏代码,你不必这么做,我只是寻找正确方向迈出的一步。我只是现在想把它实现到我的代码中。我会用我的想法更新你。再次感谢。 – user1065905

相关问题