ajax在ajax中发送请求并获得响应

时间:2017-11-22 08:19:20

标签: php ajax

早!请问我想从mySQL获取一些数据(比如使用ajax获取mySQL表的行数)。请问我该怎么办?这是我的2页。第一个向php页面发送一个数字,第二个向数据库发出请求,并将结果发送到ajax(第一个)中的页面。表voisin_par_distance有3列: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>

1 个答案:

答案 0 :(得分:0)

使用ajax的最佳和最简单的方法:

 $.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格式返回数据。 e.g。

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

我希望这会对你有所帮助。