PHP
<?php
$q=$_GET["q"];
// 设置返回json格式数据
header('content-type:application/json;charset=utf8');
//连接数据库
$link = mysqli_connect('post', 'username', 'password','database');
if (!$link){
die('Could not connect: ' . mysqli_connect_error());
}
$results = array();
// 查询数据到数组中
if($result = mysqli_query($link, "SQL")){
while ($row = mysqli_fetch_assoc($result)) {
$results[] = $row;
}
// 将数组转成json格式
echo json_encode($results);
}
// 关闭连接
mysqli_close($link);
jQuery
<html>
<head>
<script type="text/javascript">
$("button:eq(0)").click(function(){
$.ajax({
type:'GET',
url:"/test.php",
datatype:"html",
success: function(data){
$html="<table border='1'><tr><th>id</th><th>name</th><th>ctime</th></tr>";
$.each(data,function(data,test){
$html+="<tr><td>"+test.id+"</td>";
$html+="<td>"+test.name+"</td>";
$html+="<td>"+test.ctime+"</td></tr>";
});
$html+="</table>";
$("#txtHint").html($html);
}
});
});
</script>
</head>
<body>
<button >发送请求</button>
<p>
<div id="txtHint"></b></div>
</p>
</body>
</html>
JavaScript
<html>
<head>
<script type="text/javascript">
var xmlHttp
function showUser()
{
alert(location.href.substring(0,location.href.lastIndexOf('/')));
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request")
return
}
var url="https://139.219.99.200:8000/test.php"
url=url+"?sid="+Math.random()
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;
}
</script>
</head>
<body>
<button onclick="showUser()">发送请求</button>
<p>
<div id="txtHint"></div>
</p>
</body>
</html>