Esempio Database AJAX
- Pagina precedente ASP AJAX
- Pagina successiva Applicazione AJAX
AJAX può essere utilizzato per comunicare interattivamente con il database.
Esempio Database AJAX
Ecco un esempio di come una pagina web può leggere informazioni da un database tramite AJAX:
Esempio
Esempio di spiegazione - funzione showCustomer()
Quando l'utente seleziona un cliente dall'elenco a discesa sopra, viene eseguita la funzione "showCustomer()". Questa funzione viene onchange
Evento scatenato:
showCustomer
function showCustomer(str) { var xhttp; if (str == "") { document.getElementById("txtHint").innerHTML = ""; return; } xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("txtHint").innerHTML = this.responseText; } }; xhttp.open("GET", "getcustomer.asp?q=" + str, true); xhttp.send(); }
La funzione showCustomer() esegue quanto segue:
- Controllare se è stato selezionato un cliente
- Creare un oggetto XMLHttpRequest
- Creare una funzione che viene eseguita quando il server risponde
- Inviare una richiesta al file sul server
- Attenzione, il parametro q viene aggiunto all'URL (contenuto con elenco a discesa)
Pagina server AJAX
La pagina server chiamata "getcustomer.asp" è chiamata da JavaScript.
È facile riscrivere questo file server utilizzando PHP o altri linguaggi server.
Vedere l'esempio corrispondente in PHP。
Il codice sorgente di "getcustomer.asp" esegue una query verso il database e restituisce i risultati in una tabella HTML:
<% response.expires=-1 sql="SELECT * FROM CUSTOMERS WHERE CUSTOMERID=" sql=sql & "'" & request.querystring("q") & "'" set conn=Server.CreateObject("ADODB.Connection") conn.Provider="Microsoft.Jet.OLEDB.4.0" conn.Open(Server.Mappath("customers.mdb")) set rs=Server.CreateObject("ADODB.recordset") rs.Open sql,conn response.write("<table>") do until rs.EOF for each x in rs.Fields response.write("<tr><td><b>" & x.name & "</b></td>") response.write("<td>" & x.value & "</td></tr>") next rs.MoveNext loop response.write("</table>") %>
- Pagina precedente ASP AJAX
- Pagina successiva Applicazione AJAX