php将数组返回到javascript中 [英] php return array into javascript
问题描述
我进行了搜索,但是我仍然很困惑,因为我真的是php和ajax的新手,所以我希望有人可以帮助我.
I did a search but I am still confused as I am really new to php and ajax, so I was hoping someone can help me.
我正在使用一些ajax中的php脚本来访问数据库.我可以回显数据以替换网页上的元素.但是我想将数据作为数组接收,以便在javaScript中再次进行操作.
Im am using a php script within some ajax to access a database. I can echo the data to replace an element on the webpage. However I want to receive the data as an array to manipulate again in 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.
and he is the ajax/jScript used to call the php script.
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中将数据作为数组接收呢?
As you can see it replaces div2 with a table with the info. But how can I instead receive the data as an array in jScript?
欢呼
推荐答案
正如Marc B所说,SQL查询的结果是您需要从中读取以便进行JSON编码的结果句柄:
As Marc B says, the result of an SQL query is a result handle that you need to read from in order to then JSON encode:
// 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中:
In your script, use something like the following to merge that JSON into the JavaScript:
<script>
var data = <?= $jsonData ?>;
console.log(data); // or whatever you need to do with the object
</script>
这篇关于php将数组返回到javascript中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!