ajax php mysql 数据库应用 小试牛刀~~~~...
时间:2010-08-12 来源:HDecember
今天根据http://www.w3school.com.cn/ajax/ajax_database.asp学了一下AJAX里面数据库的东西.
呃.咳咳.~~~因为里面是用asp写的服务器代码,所以和上一篇一样,自己改成了php的,相当于同时学习php和AJAX了~~~~
主要问题还是php变量总是忘了要加dollar符号~~~
index.html
<html> <head> <title> new document </title> <mce:script src="./js/selectcustomers.js" mce_src="js/selectcustomers.js"></mce:script> </head> <body> <form> 请选择一位客户: <select name="customers" onchange="showCustomer(this.value)"> <option value="NULL">Please choose</option> <option value="BAIDU">Baidu</option> <option value="APPLE">Apple</option> <option value="CANON">Canon</option> </select> </form> <p> <div id="txtHint"><b>请选择客户信息,客户信息将在此列出。</b></div> </p> </body> </html>
selectcustomers.js
var xmlHttp function showCustomer(str) { if (str!="NULL") { xmlHttp=GetXmlHttpObject(); if(xmlHttp==null) { elert("您的浏览器不支持AJAX"); return; } var url="getcustomer.php"; url=url+"?q="+str; url=url+"&sid="+Math.random(); xmlHttp.onreadystatechange=stateChanged; xmlHttp.open("GET",url,true); xmlHttp.send(null); } else { document.getElementById("txtHint").innerHTML="<b>请选择客户信息</b>"; } } function stateChanged() { if(xmlHttp.readyState==4) { document.getElementById("txtHint").innerHTML=xmlHttp.responseText; } } function GetXmlHttpObject() { var xmlHttp=null; try{ xmlHttp=new XMLHttpRequest(); } catch(e) { try { xmlHttp=new ActiveXObject("Msm12.XMLHTTP"); } catch (e) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; }
getcustomer.php
<?php $con=mysql_connect("localhost","root","dian601788"); if(!$con) { die('Could not connect:'.mysql_error()); } $sql="select * from mydb.Customers where CustomerId='".$_GET["q"]."'"; $result = mysql_query($sql,$con); echo "<table border='1'>"; $row = mysql_fetch_row($result); $i=0; foreach($row as $value) { echo "<tr><td><em>".mysql_field_name($result,$i)."</em></td>"; echo "<td>".$value."</td></tr>"; $i++; } echo "</table>"; mysql_close($con); ?>