duanfu3634 2012-03-16 16:13
浏览 93
已采纳

php将数组返回javascript

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.

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.

Here is the 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);

?>

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();
}

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?

Cheers

  • 写回答

3条回答 默认 最新

  • dongshuo8756 2012-03-17 08:31
    关注

    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); 
    

    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>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 软件供应链安全是跟可靠性有关还是跟安全性有关?
  • ¥15 电脑蓝屏logfilessrtsrttrail问题
  • ¥20 关于wordpress建站遇到的问题!(语言-php)(相关搜索:云服务器)
  • ¥15 【求职】怎么找到一个周围人素质都很高不会欺负他人,并且未来月薪能够达到一万以上(技术岗)的工作?希望可以收到写有具体,可靠,已经实践过了的路径的回答?
  • ¥15 Java+vue部署版本反编译
  • ¥100 对反编译和ai熟悉的开发者。
  • ¥15 带序列特征的多输出预测模型
  • ¥15 Python 如何安装 distutils模块
  • ¥15 关于#网络#的问题:网络是从楼上引一根网线下来,接了2台傻瓜交换机,也更换了ip还是不行
  • ¥15 资源泄露软件闪退怎么解决?