如何使用php从sql查询中获取完整结果,然后使用javascript

时间:2016-11-03 00:15:50

标签: javascript php ajax

我有一个执行查询的php脚本。但结果可能是多行。如何对数据行执行json_encode,然后使用javascript获取数据并将其显示在表中?

此文件回显两条json编码行,每行代表一行

<?php  
    include("config.php");
    session_start();
    $user = $_SESSION["loggedIn"];
    $sql = "SELECT * FROM tickets where SenderName =\"$user\" OR SenderName = \"Yoon\"";
    $result = $conn->query($sql);
    while($row = $result->fetch_assoc()){
        echo json_encode($row);
    }
?>

我想使用javascript脚本和ajax来获取这两行,然后创建一个根据结果创建表的函数

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="buttons.css">
    <script type="text/javascript">
        function processData() {
            var httpRequest;
            //alert("hi there");

            if (window.XMLHttpRequest) { // Mozilla, Safari, ...
                httpRequest = new XMLHttpRequest();
                if (httpRequest.overrideMimeType) {
                    httpRequest.overrideMimeType('text/xml');
                }
            }
            else if (window.ActiveXObject) { // IE
                try {
                    httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
                    }
                catch (e) {
                    try {
                        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
                    }
                    catch (e) {}
                }
            }
            if (!httpRequest) {
                alert('Giving up :( Cannot create an XMLHTTP instance');
                return false;
            }
            httpRequest.open('GET', 'userTables.php', true);

            httpRequest.onreadystatechange = function() { 
                showTickets(httpRequest);
            }
             httpRequest.send();
        }
        function show(){
            document.getElementById("buttons").style.visibility= "hidden" ;
        }
        function showTickets(httpRequest){
            if (httpRequest.readyState == 4) {
                if (httpRequest.status == 200){
                   alert("hi there");
                   var data = JSON.parse(httpRequest.responseText);
                   alert(data["SenderName"]); //I can only get the data in a key value array if i have just one row as the result
                                    }
                else{
                    alert('Problem with request'); 
                }
            }
        }

        function createTable(httpRequest){
           //need to add innerhtml to some div that shows the table
        }



    </script>
</head>
<body>
<h1>Welcome! </h1>
 <div id="buttons">
        <button class="myButton" onclick="processData()">View My Tickets</button> 
        <button class="myButton">Submit Ticket</button> 
        <button class="myButton">Change my Password</button> 
 </div>
 <div id = "table" >

 </div>
</body>
</html>

我认为html看起来会显示一下这个表格会是这样的:

<table align="left" cellspacing="5" cellpadding="8"> 
    <tr><td align="left"><b>TicketNum</b></td>
    <td align="left"><b>Recieved</b></td>
    <td align="left"><b>SenderName</b></td>
    <td align="left"><b>Sender Email</b></td>
    <td align="left"><b>Subject</b></td>
    <td align="left"><b>Tech</b></td>
    <td align="left"><b>Status</b></td>
    <td align="left"><b>Select</b></td></tr>';

    // mysqli_fetch_array will return a row of data from the query
    // until no further data is available
    while($row = $result->fetch_assoc() ){

    echo '<tr><td align="left">' . 
    row['TicketNum'] . '</td><td align="left">' . 
    row['Recieved'] . '</td><td align="left">' .
    row['SenderName'] . '</td><td align="left">' . 
    row['SenderEmail'] . '</td><td align="left">' . 
    row['Subject'] . '</td><td align="left">' .
    row['Tech'] . '</td><td align="left">' . 
    row['Status'] . '</td><td align="left">' .

    '</td><td align="left">';
</table>';

1 个答案:

答案 0 :(得分:2)

1 确保您只在php中输出所有行

$result = $conn->query($sql);
$data = array();
while($row = $result->fetch_assoc()){
    $data[] = $row;
}
exit(json_encode($data));  // there probably is nothing else, just exit
你的javascript中的

2 只是尝试使用控制台而不是提醒 - 如果你需要帮助,这可能是一个新问题,但google&#34; console&#34;在firefox / chrome中调试。

var data = JSON.parse(httpRequest.responseText);
console.log(data); // you will have an object of the rows now

3 现在您需要使用javascript通过创建html来填充所有行...尝试这样的事情

var data = JSON.parse(httpRequest.responseText);
for (var key in data) {
    // skip loop if the property is from prototype
    if (!data.hasOwnProperty(key)) continue;

    var row = data[key];
    console.log(row);
    // now you need to make your html using javascript
    // how to do that is a new question, imho
}