Javascript 在使用 XMLHttp 更新数据库后没有从 MySQL 中提取正确的数据

Javascript not pulling correct data from MySQL after using XMLHttp to update the DB

newNet.php 运行并正确创建新条目。 netID 变量是自动递增的,因此它是自动创建的。我的目标是检索它并在 showActivities() 函数中使用它来显示刚刚创建的记录。例如它应该这样解决; showActivities(55);

问题是 SQL 总是 returns 以前的值 netID54 而不是 55;如果我说 echo $result + 1;然后,根据页面源代码,它显示 showActivities 函数正在解析正确的数字,但该函数找不到 return 数据。但是查看DB已经成功插入了。

所以一步一步来:

  1. newNet.php 运行,它将记录添加到 MySQL db
  2. 获取刚刚在 #1
  3. 中创建的 netID
  4. 将其传递给 showActivities(),后者将其显示在页面上。

我怎样才能在这里得到我想要的东西?似乎数据库的更新速度不够快,无法满足来自 showActivities() 的请求,这可能吗?

 function newNet(str) {
   str = str;
     var xmlhttp = new XMLHttpRequest();
     xmlhttp.onreadystatechange = function() {
       if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
         document.getElementById("status").innerHTML = xmlhttp.responseText;
     }}

     xmlhttp.open("POST", "newNet.php", true);
     xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
     xmlhttp.send("q="+str);

     showActivities(<?php $stmt=$db_found->prepare("select max(netID) as netID from netLog limit 1");
       $stmt->execute();
       $result=$stmt->fetchColumn();
       echo $result;
     ?>);
 }

这里有两个问题:

  1. 正如我在评论中所说,您的问题与 AJAX 的异步性质有关。该请求实际上需要时间来处理。但是您的代码将立即开始执行 showActivities,因此请求不会返回任何结果,因为那仍然是 "baking".

  2. 您的 PHP 代码在页面加载时呈现。所以旧值将从数据库中加载。在页面加载时它将是 54。您可以触发 Ajax 请求十次,netID 仍将是 54,因为 PHP 是 运行 服务器端而不是客户端。

如何解决这个问题:

你有一个 xmlhttp.onreadystatechange 函数,它监听请求并在每次完成一个步骤时触发。这称为 回调 函数。在第 4 步,比萨已经完成,200 意味着它没有被烧焦并且实际上看起来不错。当状态是这样的时候返回数据,可以访问。

 var xmlhttp = new XMLHttpRequest();
 xmlhttp.onreadystatechange = function() {
   if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
     document.getElementById("status").innerHTML = xmlhttp.responseText;
     //execute all relevant code that needs data from server from here.
     showActivities(xmlhttp.responseText);
 }}

newNet.php 中,您应该执行现在位于 showActivities() 的参数位中的 PHP 代码。在脚本完成对数据库的插入后执行此操作。

   $stmt=$db_found->prepare("select max(netID) as netID from netLog limit 1");
   $stmt->execute();
   $result=$stmt->fetchColumn();
   echo json_encode($result);

你可以json_encode结果。这样它就被打印为 JSON 到页面。我们可以将此变量加载到 JavaScript 变量中。

function showActivities(data)
{
   //remember data is a JSON string, time to convert it into JavaScript
   var netID = JSON.parse(data);
   alert(netID); //should show the highest netID
}

了解更多:

  • JSON
  • Asynchronous calls for the pizza reference and a more elaborate approach here
  • XMLHttpRequest

To sum up

  • PHP is always ran before the page is loaded and cannot be ran again without reloading the page. For that XMLHttpRequest was invented.
  • XMLHttpRequest takes time to complete, a callback must be used to process its results.