可能重复:
JSON 编码 MySQL 结果
在我的代码中,数据直接来自 SQL 到我的页面。但我希望数据应该通过 JSON 访问,在 MYSQL 和 PHP 文件之间。所以我必须在下面的代码中改变什么???
PHP代码:
<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'root', '');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test", $con);
$sql="SELECT * FROM artist_details WHERE name = '".$q."'";
$result = mysql_query($sql) ;
$num=mysql_numrows($result);
if($num!=0)
{
echo "<table border='5'>
<tr>
<th>n</th>
<th>a</th>
<th>s</th>
<th>p</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['n'] . "</td>";
echo "<td>" . $row['a'] . "</td>";
echo "<td>" . $row['s'] . "</td>";
echo "<td>" . $row['p'] . "</td>";
echo "</tr>";
}
echo "</table>";
}
else
die('record not found');
mysql_close($con);
?>
HTML 代码:
<html>
<head>
<script type="text/javascript">
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").inn…
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").inn…
}
}
xmlhttp.open("GET","http://localhost/n…
xmlhttp.send();
}
</script>
</head>
<body bgcolor="ffcccc">
<b>
<form align='center'>
Select a person:
<select name="users" onchange="showUser(this.value)">
<option value="i">i</option>
<option value="d">d</option>
<option value="r">r</option>
<option value="a">a</option>
<option value="a">a</option>
<option value="a">a</option>
</select>
</form>
<div id="txtHint" align='center'><font color="3333ff">Person info will be listed here.<font></div>
</body>
</html>
.