我做了一个搜索,但我仍然感到困惑,因为我真的很新的php和ajax,所以我希望有人能帮助我。
我正在使用一些ajax中的php脚本来访问数据库。我可以回显数据来替换网页上的元素。但是,我希望以数组的形式接收数据,以便在javaScript中再次操作。
这是php
<?php $q=$_GET["q"];
$con = mysql_connect('server', 'name', 'pass'); if (!$con) //don't connect { die('Could not connect: ' . mysql_error()); //give error }
mysql_select_db("database", $con); //select the MySQL database
$sql="SELECT * FROM table WHERE field = '".$q."'";
$result = mysql_query($sql); //$result is an array
$response = $result;
echo json_encode($response);
echo "<table border='1'>
<tr>
<th>Heading1</th>
<th>Heading2</th>
<th>Heading3</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['field1'] . "</td>";
echo "<td>" . $row['field2'] . "</td>";
echo "<td>" . $row['field3'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>他就是用来调用php脚本的ajax/jScript。
function func(var)
{
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200) //ready
{
document.getElementById("div2").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getTest.php?q=" + var,true);
xmlhttp.send();
}正如您所看到的,它用一个包含信息的表替换了div2。但是如何才能在jScript中以数组形式接收数据呢?
干杯
发布于 2012-03-17 16:31:47
正如Marc B所说,SQL查询的结果是一个结果句柄,您需要从中读取,然后进行JSON编码:
// run the query
$result = mysql_query("SELECT * FROM table WHERE field = '{$q}'");
// fetch all results into an array
$response = array();
while($row = mysql_fetch_assoc($result)) $response[] = $row;
// save the JSON encoded array
$jsonData = json_encode($response); 在脚本中,使用类似以下内容将该JSON合并到JavaScript中:
<script>
var data = <?= $jsonData ?>;
console.log(data); // or whatever you need to do with the object
</script>https://stackoverflow.com/questions/9740775
复制相似问题