2017-11-22 1 views
0

아침! 나는 AJAX를 사용하여 mySQL 테이블의 행 수를 얻는 것과 같이 mySQL에서 데이터를 얻고 싶다. 제발 어떻게 할 수 있니? 여기 내 2 페이지가 있습니다. 첫 번째는 php 페이지로 번호를 보내고 두 번째는 데이터베이스에 요청을 보내고 그 결과를 ajax (첫 번째 페이지)의 페이지로 보냅니다. voisin_par_distance 테이블에는 cel_id, cel_id_1 및 cel_id_2 감사의 세 가지 열이 있습니다.아약스가 아약스에서 요청을 보내고 응답을 받으십시오.

<!DOCTYPE html> 
<html> 
<body> 
<script> 
var xhr1 = new XMLHttpRequest(); 
var i=1; 
var j=4; 
xhr1.onreadystatechange = function() { 
    if (xhr1.status == 200 && xhr1.readyState == 4) { 
     document.getElementById('content').innerHTML = xhr1.responseText; 
    } 
}; 
xhr1.open('GET', 'test.php?i='+i+'&j='+j, false); 
xhr1.send(''); 
</script> 
<?php 
    // I would line to get for example the number of rows of table voisin_par_distance which is returned by test.php 
    $m = (int) $_GET['n']; 
    echo $m; 
?> 
</body> 
</html> 

이것은 동일한 디렉토리에있는 PHP 페이지입니다.

<?php 
$dbname='BD'; 
try { 
    $bdd = new PDO('mysql:host=localhost;dbname=BD', 'root', ''); 
} 
catch (PDOException $e) { 
    die("Could not connect to the database $dbname :" . $e->getMessage()); 
} 

$i = (int) $_GET['i']; 
$j = (int) $_GET['j']; 
    //to select the number of rows of my table 
$req = $bdd->prepare("SELECT serveur FROM voisin_par_distance WHERE cel_id_1=':cel_id_1' AND cel_id_2=':cel_id_2'"); 
$req->execute(array(
    'cel_id_1' => $i, 
    'cel_id_2' => $j 
)); 
$nbre_ligne = count($req); 

?> 
<!DOCTYPE html> 
<html> 
<body> 
<script> 
var nbre_ligne = <?php echo $nbre_ligne; ?> 
var xhr = new XMLHttpRequest(); 
var a = 2; 
xhr.onreadystatechange = function() { 
    if (xhr.status == 200 && xhr.readyState == 4) { 
     document.getElementById('content').innerHTML = xhr.responseText; 
    } 
}; 
xhr.open('GET', 'show_map.php?n='+nbre_ligne); 
xhr.send(''); 
</script> 
</body> 
</html> 

답변

0

가장 쉬운 방법은 아약스 사용 :

$.ajax({// on an event 
    type: "GET", 
    url: "test.php", #with valid path 
    data: {col1: "value1", col2: "value2"}, 
    cache: false, 
    success: function (responce) { 
    // alert your response to check data 
     if (responce.length > 0) { 
      var data = JSON.parse(responce); // Parse JSON 
      //Your logic here 
     } 
    } 
}); 

당신의 PHP 파일에서 JSON 형식의 데이터를 반환합니다. 예 :

echo json_encode(array('col1' => $val, 'col2' => $val2)); 
exit; 

이 정보가 도움이되기를 바랍니다.

+0

도움 주셔서 감사합니다. 콘솔의 메시지 : ReferenceError : $가 정의되지 않았습니다. my_page : 559 : 1 오류 : 그래프 컨테이너 요소를 찾을 수 없습니다. – atangopascall

관련 문제