많은 포럼에서 내 답변을 찾으려고했지만 한 가지 주요 답변을 찾았지만 어떤 이유로 든 제 경우에는 작동하지 않습니다.JS 파일을 PHP 파일에 포함하십시오.
웹 개발에 처음 참가했습니다. JSON 문자열로 표시되는 제품 목록을 사용하고 제품과 함께 HTML 표를 반환하는 매우 간단한 JS 프로그램을 작성하려고합니다. DB 데이터를 사용하려면 AJAX를 사용하고 있습니다. 지금까지 PHP와 JS 파일이라는 두 개의 파일이 있습니다.
JS 파일 (show.js)이 호출하는 서버의 페이지는 "testmysql.php"라는 PHP 파일입니다.
문제는 두 파일에서 공유 매개 변수가 있기 때문에 JS 파일을 PHP 파일에 포함해야한다는 것입니다.
** "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>
문제가있는 행입니다 스크립트 유형 = "텍스트/자바 스크립트" src = "show.js">이며 어떤 이유로 인해 의 오류를 반환합니다. 정의되지 않은 색인 : q, q는 두 파일의 공유 매개 변수입니다. 제 질문은 이해할 수 있기를 바랍니다. 감사합니다.
코드에'txtHint' id가 없습니다. 그 위치는 어디입니까? 당신은 분명히 튜토리얼을 따라 갔지만 그것을 따르지 않았습니다 * "to T"*. showUser()를 어디에서 호출할까요? 여기에 코드가 없습니다. –
www.stackoverflow.com/questions/23740548/how-to-pass-variables-and-data-from-php-to-javascript – Iceman
나는 충분히 오래 여기에 머물렀다. –