Ajax结果转换为字符串无效



如何将结果转换为字符串以在js中使用?我做了一个AJAX连接,需要所有记录的数量。

server3.php:应该将结果转换为int.

<?php
$antwort = $_GET['aa'];
$con = mysqli_connect('localhost','root','','loginpage');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"loginpage");
$sql="SELECT COUNT(id) AS anzahl FROM frage";
$result = mysqli_query($con,$sql);
$row = intval($result);
echo "<p>" . $row . "</p>";
mysqli_close($con);
?>

js.js:我也试过这个。

function anzahlFragen() {
var xmlhttp2 = new XMLHttpRequest();
xmlhttp2.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
fragenAnzahl = this.responseText;
}
}
xmlhttp2.open("GET","server3.php",true);
xmlhttp2.send();
}

您尚未获取结果数据。之后

$result = mysqli_query($con,$sql);

您需要获取列值,这可以使用mysqli_fetch_array:来完成

$row = mysqli_fetch_array($result);
$count = $row[0];

然后你可以回显计数:

echo "<p>" . $count . "</p>";

您需要从数据库中提取行,类似于:

$sql = "SELECT COUNT(id) AS anzahl FROM frage";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_assoc($result);
// access your value by alias in the query
echo "<p>" . $row['anzahl'] . "</p>";
mysqli_close($con);

最新更新