问题在于时机。有两个非常独立的执行上下文值得考虑来理解您的问题:
- 页面构建 (PHP) - Web 服务器创建 HTML 发送到浏览器;
- 用户交互 (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)。你的脚本应该得到seat
URL参数通过$_GET['seat']
并在您的查询中使用它。
根据 Madara 的评论,不要使用mysql_query
直接使用它,因为它已被弃用,请使用更好的东西。