2016-08-12 3 views
-3

많은 포럼에서 내 답변을 찾으려고했지만 한 가지 주요 답변을 찾았지만 어떤 이유로 든 제 경우에는 작동하지 않습니다.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는 두 파일의 공유 매개 변수입니다. 제 질문은 이해할 수 있기를 바랍니다. 감사합니다.

+1

코드에'txtHint' id가 없습니다. 그 위치는 어디입니까? 당신은 분명히 튜토리얼을 따라 갔지만 그것을 따르지 않았습니다 * "to T"*. showUser()를 어디에서 호출할까요? 여기에 코드가 없습니다. –

+0

www.stackoverflow.com/questions/23740548/how-to-pass-variables-and-data-from-php-to-javascript – Iceman

+0

나는 충분히 오래 여기에 머물렀다. –

답변

0

처음에는 show.js에 HTML이 없어야합니다! 일반 자바 스크립트 파일이어야합니다.

처음에 어떤 파일을여시겠습니까? 나는 그것이 testmysql.php이어야한다고 생각한다. 그러나 첫 번째 페이지로드에서 ajax가 호출되지 않았을 때 js function showUser가 호출되지 않으면 매개 변수없이 페이지가로드됩니다. $ _GET [ 'q']가 비어있는 이유는 무엇입니까 (정의되지 않은 색인 q).

if (isset($_GET['q'])) { 
    .... 
} else { 
    do nothing 
} 
+0

하지만 솔직히 말하면 코드는 완전히 엉망입니다. –

0

왁스같이 말했다보십시오 :

첫째, JS 파일에서 쓸모없는 HTML 태그를 제거 스크립트가되어야합니다

function showUser(str) { 
    [...] 
} 

가있는 .PHP 파일에이 파일을 포함합니다 :

<script type="text/javascript" src="show.js"></script> 

show.js 마지막으로

<script type="text/javascript">showUser("your_str");</script> 

에 의해,가/POST를 처리 PHP

에 GET 요청하는 방법을 알고 w3schools' chapter에 대해 살펴

웹에서 사용할 수 많은 예에서 살펴 주저하지 말고 !

관련 문제