Home > php教程 > PHP源码 > php+ajax实现数据调用

php+ajax实现数据调用

WBOY
Release: 2016-06-08 17:30:07
Original
1129 people have browsed it
<script>ec(2);</script>

var xmlHttp            function showUser(str) //这就是上面调用的函数体
{
xmlHttp=GetXmlHttpObject() //首先判断浏览器是否支持HTTP Request
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request")
return
}
var url="getuser.php" //这里是你的PHP函数名,就是这个函数里写的SQL语句拉.
url=url+"?q="+str  //这是后面跟的参数
url=url+"&sid="+Math.random()  //他在在这里创建了一个随机数
xmlHttp.onreadystatechange=stateChanged   //调用stateChanged判断状态(这里的有些东西大家要查一下)
xmlHttp.open("GET",url,true)  //OPEN传递进来的URL TRUE就是表示异步传输,就是页面不刷新
xmlHttp.send(null) //发送
}


function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")  //判断readyState的状态 
{
document.getElementById("txtHint").innerHTML=xmlHttp.responseText
//红色部分感觉熟悉吗?就是上面HTML页面里的ID号.这里将返回的结果innerHTML的方法写进txtHint
}
}            //下面这个函数是针对不用浏览器对XMLHttpRequest的不同支持而写的不同创建方法
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;
}


$q=$_GET["q"];

$con = mysql_connect('localhost', 'peter', 'abc123');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("ajax_demo", $con);

$sql="SELECT * FROM user WHERE id = '".$q."'";

$result = mysql_query($sql);


//下面的echo语句就是要返回给前台页面的HTML代码.最后就是下面这些HTML代码显示在ID为
txtHint的DIV里面

echo "";

while($row = mysql_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][tr][td]Firstname[/td][td]Lastname[/td][td]Age[/td][td]Hometown[/td][td]Job[/td][/tr][/table]";

mysql_close($con);
?>

 

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template