【发布时间】:2016-08-12 13:04:21
【问题描述】:
尝试在许多论坛中找到我的答案,找到了一个主要答案,但由于某种原因在我的情况下不起作用。
对 Web 开发很陌生。我正在尝试编写一个非常简单的 JS 程序,它使用一个产品列表(由 JSON 字符串表示),并返回一个包含产品的 HTML 表。为了使用数据库数据,我使用了 AJAX。 到目前为止,我有两个文件,一个 PHP 文件和一个 JS 文件。
JS文件(show.js)调用的服务器上的页面是一个名为“testmysql.php”的PHP文件。
问题是我在两个文件中都有一个共享参数,因此我需要在 PHP 文件中包含 JS 文件。
**"show.js" : **
<html>
<head>
<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","testmysql.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
</html>
**“testmysql.php”:**
<html>
<head>
<script type="text/javascript" src="show.js"></script>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, td, th {
border: 1px solid black;
padding: 5px;
}
th {text-align: left;}
</style>
</head>
<body>
<?php
//Sample Database Connection Script
//Setup connection variables, such as database username
//and password
$hostname="localhost";
$username="root";
$password="";
$dbname="grocery";
$usertable="grocery";
$yourfield = "NAME";
$q = intval($_GET['q']);
//Connect to the database
$connection = mysqli_connect($hostname, $username, $password);
mysqli_select_db($connection, $dbname);
$query="SELECT * FROM user WHERE id = '".$q."'";
$result = mysqli_query($connection,$query);
echo "<table>
<tr>
<th>Name</th>
<th>Price</th>
<th>Amount</th>
</tr>";
if($result){
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['NAME'] . "</td>";
echo "<td>" . $row['PRICE'] . "</td>";
echo "<td>" . $row['AMOUNT'] . "</td>";
echo "</tr>";
}
}
echo "</table>";
mysqli_close($connection);
/*
//Setup our query
//$query = "SELECT * FROM $usertable";
Run the Query
$result = mysqli_query($connection,$query);
//If the query returned results, loop through
// each result
if($result)
{
while($row = mysqli_fetch_array($result))
{
$name = $row["$yourfield"];
echo "Name: " . $name;
}
}
*/
?>
</body>
</html>
有问题的行是script type="text/javascript" src="show.js">,由于某种原因它返回未定义索引的错误:q,而q是共享的两个文件中的参数。 希望我的问题可以理解,谢谢。
【问题讨论】:
-
一方面,我在您的代码中看不到
txtHintid。它位于哪里?您显然遵循了一个教程,但没有遵循它“to a T”。你在哪里打电话showUser()?这里缺少代码。 -
我在这里待得够久了。
-
另外,您返回的是 HTML,而不是 JSON 字符串。我在任何地方都没有看到 JSON。
-
你在调用 showUser() 吗?在哪里 ?如果你还没有,请放完整的代码。
标签: javascript php jquery ajax node.js