从php发回数据

时间:2014-11-06 10:27:18

标签: javascript php mysql ajax

我尝试this教程使用ajax和php从我的mysql数据库发送/检索数据。 这是ajax部分:

                <script>
                    function showUser(str) {
                      if (str=="") {
                        document.getElementById("txtHint").innerHTML="";
                        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").innerHTML=xmlhttp.responseText;
                        }
                      }
                      xmlhttp.open("GET","suchen_ma.php?id="+str,true);
                      xmlhttp.send();
                    }
                </script>

.php文件如下所示:

<?php

//Connection Details
$username = 'root';
$password = '';
$hostname = 'localhost';
$databasename = 'plzdb';


$id             = ($_GET['id']);

//Connection-string
$con = mysqli_connect($hostname,$username,$password,$databasename);

//SQL Query
$sql = "SELECT per_vorname,per_nachname from plz_person
        WHERE per_id = $id";
$result = mysqli_query($con,$sql);
echo "<table border='0'>
<tr>
<th></th>
<th></th>
</tr>";

while($row = mysqli_fetch_array($result)) {
  echo "<tr>";
  echo "<td>" . $row['per_vorname'] . "</td>";
  echo "<td>" . $row['per_nachname'] . "</td>";
  echo "</tr>";
}
echo "</table>";

mysqli_close($con);
?>

数据在php文件中格式化,但我想发送&#34; raw&#34;数据返回到html并将其显示在列表中并使用css格式化。不幸的是我不知道该怎么做

1 个答案:

答案 0 :(得分:0)

只需将数据作为JSON:

返回
$sql = "SELECT per_vorname,per_nachname from plz_person
        WHERE per_id = " . mysqli_real_escape_string($con, $id);
$result = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($result)) {

    $persons[] = array(
        "vorname" => $row['per_vorname'],
        "per_nachname" => $row['per_nachname']
    );
}
echo json_encode($persons);

然后在javascript中创建一个循环来构建HTML。

注意:通过转义字符串来避免sql注入。