Ajax 结果转换为字符串无效

Ajax result converting into string doesnt work

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

server3.php: 结果应转换为整数。

<?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:我也用 this.response 试过了。

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();
}

您需要从数据库中获取行,例如:

$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);

您还没有获取结果数据。之后

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

您需要获取列值,您可以使用 mysqli_fetch_array:

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

然后你可以回显计数:

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