0

可能重复:
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>

.

4

2 回答 2

0

最好使用 jQuery Ajax。它为您完成所有基础和检查。你开始进行ajax调用。转到 jQuery 并阅读文档:http ://api.jquery.com/jQuery.get/

例子:

//PHP Code data.php
$result = array();
while($row = mysql_fetch_array($result))
{
   $result[] = $row;
}


return json_encode($result);


//Jquery Code
<script>
$.get("data.php", function(result){
    var rows = JSON.parse(result);

    //do the loop and inject into html table
    }); 
</script>
于 2012-10-10T13:07:13.020 回答
0

在 PHP 方面,您需要使用 json_encode 函数将数组转换为 json 字符串。

$data = array();
while($row = mysql_fetch_array($result))
{
    $data[] = $row;
}

echo json_encode($data); 

然后,您可以更改 javascript 中的代码以从响应中获取 json 对象。

var jsonResponse = JSON.parse(req.responseText);

但是,您可以使用一些好的 JS 库(如 jQuery)进行 Ajax 操作,以便与不同的浏览器兼容。此外,最好使用 mysqli 或 PDO 而不是像其他人所说的 mysql 扩展。

于 2012-10-10T13:00:26.020 回答