Javascript变量控制PHP数据库搜索

时间:2018-11-15 11:50:07

标签: javascript php html database livesearch

我目前有一个SQL数据库,实际上我想通过Javascript进行实时搜索。我对如何实现以下内容感到有些困惑:

JAVASCRIPT / HTML(index.php):

<form>
  Centre (cents):<br>
  <input type="number" id="centreCents" value="0"><br>
  Range (cents):<br>
  <input type="number" id="rangeCents" value="0">
</form>

<button onclick="myFunction()">Search</button>

<table>
    <tr>
        <th>ID</th>
        <th>CENTS</th>
        <th>HD</th>

    </tr>
    <tbody id="data">

    </tbody>
</table>

<script>

function myFunction(){
    // call ajax
    var ajax = new XMLHttpRequest();
    var method = "GET";
    var url = "data.php";
    var asynchronous = true;

    ajax.open(method, url, asynchronous);

    // sending request 
    ajax.send();

    // receiving response from data.php
    ajax.onreadystatechange = function()
    {
        if (this.readyState == 4 && this.status == 200){
            // converting JSON back to array
            var data = JSON.parse(this.responseText);
            console.log(data); // for debugging

            // html value for <tbody>
            var html = "";
            // loop through the data
            for (var a = 0; a < data.length; a++){
                var ID = data[a].id;
                var cents = data[a].cents;
                var HD = data[a].hd;

                // storing in html

                html += "<tr>";
                    html += "<td>" + ID + "</td>";
                    html += "<td>" + cents + "</td>";
                    html += "<td>" + HD + "</td>";
                html += "</tr>"
            }
            // replacing the body of <tbody> of <table>
            document.getElementById("data").innerHTML = html;

        }
    }
}
</script>

PHP(data.php):

<?php

//getting data from databank 

$dbServername = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName = "enharmonics";

$conn = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);

// getting data from table

$centSearch = "SELECT * FROM enharmonictable WHERE cents>=385 AND cents<=388 ORDER BY hd ASC;";
$result = mysqli_query($conn, $centSearch);

// storing in array

$data = array();
$HDdata = array();
while ($row = mysqli_fetch_assoc($result)) {
    $data[] = $row;
}

// returning response in JSON format

echo json_encode($data);

理想情况下,$ centSearch的数值将由html中的数字框确定为 centreCents-rangeCents centreCents + rangeCents 。然后,再次按下该按钮,一切将运行(更新)。寻找一些指导-真的希望有可能!到目前为止,一切进展顺利。

0 个答案:

没有答案