[英]ajax send a request in ajax and get the response
Morning! 早上! Please i will like to get some data from mySQL(like getting the number of rows of a mySQL table using ajax). 请我想从mySQL获取一些数据(例如使用ajax获取mySQL表的行数)。 Please how can i do it? 请问我该怎么做? Here are my 2 pages. 这是我的2页。 The first one send a number to the php page and the second one do a request to the database and send the result to the page in ajax(the first one). 第一个向php页面发送一个数字,第二个向数据库发出请求,并将结果发送到ajax页面(第一个)。 The table voisin_par_distance has 3 columns: cel_id, cel_id_1 and cel_id_2 Thanks. 表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>
and this is the php page which is in the same directory. 这是位于同一目录中的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>
Best and Easy way to use ajax: 使用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
}
}
});
In Your PHP file, return data in json format. 在您的PHP文件中,以json格式返回数据。 eg 例如
echo json_encode(array('col1' => $val, 'col2' => $val2));
exit;
I hope this will help you. 我希望这能帮到您。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.