Latest web development tutorials

ฐานข้อมูล AJAX

AJAX สามารถใช้สำหรับการสื่อสารโต้ตอบกับฐานข้อมูล


ฐานข้อมูลเช่น AJAX

ตัวอย่างต่อไปนี้จะแสดงให้เห็นว่าหน้าเว็บผ่านทาง AJAX อ่านข้อมูลจากฐานข้อมูล:

ตัวอย่าง


Customer info will be listed here...


ตัวอย่างอธิบาย - หน้า HTML

เมื่อผู้ใช้ในรายการแบบหล่นลงข้างต้นให้เลือกลูกค้าดำเนินการตั้งชื่อว่า "showCustomer ()" ฟังก์ชั่น ฟังก์ชั่นนี้โดย "onChange" เหตุการณ์จะถูกเรียก:

<!DOCTYPE html>
<html>
<head>
<script>
function showCustomer(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for 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","getcustomer.asp?q="+str,true);
xmlhttp.send();
}
</script>
</head
<body>

<form>
<select name="customers" onchange="showCustomer(this.value)">
<option value="">Select a customer:</option>
<option value="ALFKI">Alfreds Futterkiste</option>
<option value="NORTS ">North/South</option>
<option value="WOLZA">Wolski Zajazd</option>
</select>
</form>
<br>
<div id="txtHint">Customer info will be listed here...</div>

</body>
</html>

มาอธิบายว่า:

ถ้าคุณไม่ได้เลือกลูกค้า (str.length == 0), ฟังก์ชั่นนั้นจะชัดเจน txtHint ตัวยึดแล้วออกจากฟังก์ชั่น

หากคุณเลือกลูกค้าแล้ว showCustomer () ฟังก์ชันทำตามขั้นตอนต่อไปนี้:

  • สร้างวัตถุ XMLHttpRequest
  • สร้างฟังก์ชั่นเมื่อเซิร์ฟเวอร์ที่อยู่พร้อมที่จะดำเนินการตอบสนอง
  • ไฟล์บนเซิร์ฟเวอร์เพื่อส่งคำขอ
  • โปรดทราบเพิ่มต่อท้ายพารามิเตอร์ URL (Q) (ที่มีเนื้อหาของรายการแบบหล่นลง)

ASP ไฟล์

เซิร์ฟเวอร์ดังกล่าวข้างต้นผ่าน JavaScript เรียกหน้านี้ถูกเรียกว่า "getcustomer.asp" ไฟล์ ASP

"Getcustomer.asp" รหัสที่มาทำงานแบบสอบถามกับฐานข้อมูลแล้วส่งกลับผลลัพธ์ในตาราง 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("/db/northwind.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>")
%>