我如何使网站等待我的Ajax文件发送回一个值,而不是打印未定义的值? [重复]

问题描述 投票:0回答:3

所以我有这个功能,我希望程序等待它返回一个值,而不是给出undefined。

function savedNumberOfLessonInDay(dayID){
     var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
          if (this.readyState == 4 && this.status == 200) {
            document.getElementById('demo4').innerHTML = this.responseText; //Returns the right number
            return this.responseText;
        }
      };
      var PageToSendTo = "AJAX/countLessonInDay.php?";
    var MyVariable = dayID;
    var VariablePlaceholder = "GETDayID=";
    var UrlToSend = PageToSendTo + VariablePlaceholder + MyVariable;
      xhttp.open("GET", UrlToSend, false);
      xhttp.send();
   }
<?php

require '../notWebsite/dbh.php';
session_start();
$dayID = (int)$_GET['GETDayID'];

$sqlCount = "SELECT COUNT(lessonID) FROM daylesson WHERE dayID = ?";
  $stmt = mysqli_stmt_init($conn);

  if(!mysqli_stmt_prepare($stmt, $sqlCount)) {
   header("Location: ../GymnasieArbeteHemsida.php?error=countError");
    exit();
  }
  else {
 mysqli_stmt_bind_param($stmt, "i", $dayID);//Puts in variable in question
   mysqli_stmt_execute($stmt);//Executes the question
mysqli_stmt_bind_result($stmt, $result);//Binds the reuslt of the question to the variable $result
if(mysqli_stmt_fetch($stmt)){//If the result of the question can be recieved
  echo $result;//Send the result to the website
}


        exit();
  }

  mysqli_stmt_close($stmt);
  mysqli_close($conn);



 ?>
  document.getElementById('demo').innerHTML = 'test' + savedNumberOfLessonInDay(number);

此代码将testundefined返回给demo,但将16(这是我后面的数字)返回给demo4。如何使test16返回test而不是testundefined?

javascript php ajax
3个回答
0
投票

您无法拨打savedNumberOfLessonInDay(number)来获取电话号码。您正在尝试使用return this.responseText;来执行此操作,但是直到对服务器的请求完成后才会触发。

您可以使用Promises解决此问题。

function savedNumberOfLessonInDay(dayID){
     return new Promise((resolve) => {
     var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
          if (this.readyState == 4 && this.status == 200) {
            document.getElementById('demo4').innerHTML = this.responseText; //Returns the right number
            resolve(this.responseText);
        }
      };
      var PageToSendTo = "AJAX/countLessonInDay.php?";
    var MyVariable = dayID;
    var VariablePlaceholder = "GETDayID=";
    var UrlToSend = PageToSendTo + VariablePlaceholder + MyVariable;
      xhttp.open("GET", UrlToSend, false);
      xhttp.send();
     });
   }

并使用await调用它:

  document.getElementById('demo').innerHTML = 'test' + await savedNumberOfLessonInDay(number);

或者,如果由于某些原因您不能使用await

  savedNumberOfLessonInDay(number).then((response) => {
      document.getElementById('demo').innerHTML = 'test' + response;
  });

0
投票

函数saveNumberOfLessonInDay()不会等待ajax完成。因此,您需要在回调函数xhttp.onreadystatechange中设置用于演示的html。

无需过多更改您的实现,您只需修改代码即可:

function savedNumberOfLessonInDay(dayID){
 var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        document.getElementById('demo4').innerHTML = this.responseText; //Returns the right number
        document.getElementById('demo').innerHTML = 'test' + this.responseText;
    }
  };
  var PageToSendTo = "AJAX/countLessonInDay.php?";
var MyVariable = dayID;
var VariablePlaceholder = "GETDayID=";
var UrlToSend = PageToSendTo + VariablePlaceholder + MyVariable;
  xhttp.open("GET", UrlToSend, false);
  xhttp.send();

}

然后只需调用该函数,而不要尝试设置

savedNumberOfLessonInDay(number);

0
投票

尝试使用异步/等待,这是如何使用它。 https://javascript.info/async-await

© www.soinside.com 2019 - 2024. All rights reserved.