2012-09-17 82 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

相關問題