如何更新此脚本以尊重JQuery AJAX语法?

时间:2016-02-26 16:11:22

标签: javascript php jquery ajax

我有一个有效的脚本,它接受一个选项值,将它存储在一个变量q中,并向一个查询数据库的php脚本发送一个xmlhttp get调用,返回带有结果的html表。我正在尝试用get方法格式将此更新为jQuery.ajax()...感谢任何帮助。

example_ajax_html_js.php:

<html>
<head>
<script src="//code.jquery.com/jquery-2.2.1.min.js"></script>
<script>
function showUser(str) {
    if (str == "") {
        document.getElementById("txtHint").innerHTML = "";
        return;
    } else { 
        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","/getuser.php?q="+str,true);
        xmlhttp.send();
    }
}
</script>
</head>
<body>

<form>
<select name="users" onchange="showUser(this.value)">
  <option value="">Select a person:</option>
  <option value="Sophia">Sophia</option>
  <option value="Daniel">Daniel</option>
  </select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here...</b></div>

</body>
</html>

调用getuser.php:

<!DOCTYPE html>
<html>
<head>
<style>
table {
    width: 100%;
    border-collapse: collapse;
}

table, td, th {
    border: 1px solid black;
    padding: 5px;
}

th {text-align: left;}
</style>
</head>
<body>

<?php
$q = $_GET['q'];

// connect to db

$sql="SELECT * FROM table WHERE first = '".$q."'";
$result = mysqli_query($web_dbi, $sql) or die("Error " . mysqli_error($web_dbi));

echo "<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>extrainfo1</th>
<th>extrainfo2</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
    echo "<tr>";
    echo "<td>" . $row['first'] . "</td>";
    echo "<td>" . $row['last'] . "</td>";
    echo "<td>" . $row['extrainfo1'] . "</td>";
    echo "<td>" . $row['extrainfo2'] . "</td>";
    echo "</tr>";
}
echo "</table>";
mysqli_close($web_dbi);
?>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

比使用jQuery的ajax方法更容易,我使用load方法。让你的工作变得轻而易举:

function showUser(str) {
    if (str == "") {
        $("#txtHint").html("");
        return;
    }

    $("#txtHint").load("/getuser.php?q="+str);
}

就是这样!

http://api.jquery.com/load/