Il miglior tutorial PHP e MySQL esempio AJAX Nel 2024, in questo tutorial puoi imparare istanza di database AJAX,Esempi,Esempi spiegano - database MySQL,pagina HTML - Esempi spiegano,PHP file,
AJAX può essere utilizzato per la comunicazione interattiva con il database.
Gli esempi che seguono dimostreranno come una pagina web tramite la tecnologia AJAX leggere le informazioni dal database:
Nel precedente esempio, usiamo la tabella del database è la seguente:
id | FirstName | LastName | Age | Hometown | Job |
---|---|---|---|---|---|
1 | Peter | Griffin | 41 | Quahog | Brewery |
2 | Lois | Griffin | 40 | Newport | Piano Teacher |
3 | Joseph | Swanson | 39 | Quahog | Police Officer |
4 | Glenn | Quagmire | 41 | Quahog | Pilot |
Quando un utente nell'elenco a discesa sopra, selezionare un utente, eseguirà il nome di ") ShowUser (" la funzione. Questa funzione dall'evento "onchange" viene attivato:
<html> <head> <script> function showUser(str) { if (str=="") { document.getElementById("txtHint").innerHTML=""; return; } if (window.XMLHttpRequest) { // IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码 xmlhttp=new XMLHttpRequest(); } else { // IE6, IE5 浏览器执行代码 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("txtHint").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","getuser.php?q="+str,true); xmlhttp.send(); } </script> </head> <body> <form> <select name="users" onchange="showUser(this.value)"> <option value="">Select a person:</option> <option value="1">Peter Griffin</option> <option value="2">Lois Griffin</option> <option value="3">Glenn Quagmire</option> <option value="4">Joseph Swanson</option> </select> </form> <br> <div id="txtHint"><b>Person info will be listed here.</b></div> </body> </html>
Funzione ShowUser () esegue le seguenti operazioni:
I server di cui sopra attraverso JavaScript chiamando questa pagina è chiamato file PHP "getuser.php".
Il codice sorgente verrà eseguito "getuser.php" in una sola volta per query di database MySQL e restituisce i risultati in una tabella HTML:
<?php $q=$_GET["q"]; $con = mysqli_connect('localhost','peter','abc123','my_db'); if (!$con) { die('Could not connect: ' . mysqli_error($con)); } mysqli_select_db($con,"ajax_demo"); $sql="SELECT * FROM user WHERE id = '".$q."'"; $result = mysqli_query($con,$sql); echo "<table border='1'> <tr> <th>Firstname</th> <th>Lastname</th> <th>Age</th> <th>Hometown</th> <th>Job</th> </tr>"; while($row = mysqli_fetch_array($result)) { echo "<tr>"; echo "<td>" . $row['FirstName'] . "</td>"; echo "<td>" . $row['LastName'] . "</td>"; echo "<td>" . $row['Age'] . "</td>"; echo "<td>" . $row['Hometown'] . "</td>"; echo "<td>" . $row['Job'] . "</td>"; echo "</tr>"; } echo "</table>"; mysqli_close($con); ?>
Spiegazione: Quando una query viene inviata da JavaScript per file PHP si verificherà: