日期:2014-05-16  浏览次数:20594 次

Ajax如何调用后台php代码访问数据库
Ajax如何调用数据库,这里我用的JS代码是function check{
var xmlHttp

function showUser(str)

xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request")
return
}
var url="getuser.php" //getuser.php是我的PHP文件,功能是链接数据库并且访问
xmlHttp.onreadystatechange=stateChanged 
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}

function stateChanged() 

if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")

document.getElementById("txtHint").innerHTML=xmlHttp.responseText 

}

function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
//Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}

}
php代码是:<?php

//连接数据库的函数
$con = mysql_connect('localhost', 'root', '123');
if (!$con)
 {
 die('Could not connect: ' . mysql_error());
 }

mysql_select_db("storage", $con);

$sql="SELECT * FROM user_main";

$result = mysql_query($sql);

echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
</tr>";

while($row = mysql_fetch_array($result))
 {
 echo "<tr>";
 echo "<td>" . $row['user_id'] . "</td>";
 echo "<td>" . $row['user_name'] . "</td>";
 echo "<td>" . $row['password'] . "</td>";
 echo "<td>" . $row['text'] . "</td>";
 echo "</tr>";
 }
echo "</table>";

mysql_close($con);
?>
html代码是:<html>
<head>
<script src="selectuser.js"></script>
</head>
<body>

<form method="post" onSubmit="return showUser();"> 
Select a User:
<input type="submit" name="users" value="提交" >

</form>
<p>
<div><b>User info will be listed here.</b></div>
</p>

</body>
</html>
求各位大侠指教

------解决方案--------------------
你的代码写的真让人蛋疼,重写吧,逻辑有些混乱
------解决方案--------------------
要自己去下载两个文件

a.js
JScript code

function load() { document.getElementById("load").display="none"; } 

 var t = "bb";
 $.ajax({
    url: "a.php",//获取数据文件路径
    type: "post",              //提交方式
    data:"selectID="+ escape(t) +"", //传递参数
    success: function(data,textStatus){
    if(data==""){
   $('#dv').css('background', '#ffffff').html("暂无数据").show();
   }else
   {
    $('#dv').css('background', '#ffffff').html(data).show();
}
//显示区域,隐藏其它
    $("#dv").html(data);

   },
     error: function(o){
}
});