如何让网站等待我的 ajax 文件发回一个值而不是打印 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 而不是 testundefined?


开心每一天1111
浏览 127回答 3
3回答

慕莱坞森

你不能打电话savedNumberOfLessonInDay(number)来获取号码。您正在尝试使用 执行此操作return this.responseText;,但在对服务器的请求完成之前不会触发。你可以使用 Promises 来解决这个问题。function savedNumberOfLessonInDay(dayID){&nbsp; &nbsp; &nbsp;return new Promise((resolve) => {&nbsp; &nbsp; &nbsp;var xhttp = new XMLHttpRequest();&nbsp; &nbsp; &nbsp; xhttp.onreadystatechange = function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (this.readyState == 4 && this.status == 200) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById('demo4').innerHTML = this.responseText; //Returns the right number&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; resolve(this.responseText);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; var PageToSendTo = "AJAX/countLessonInDay.php?";&nbsp; &nbsp; var MyVariable = dayID;&nbsp; &nbsp; var VariablePlaceholder = "GETDayID=";&nbsp; &nbsp; var UrlToSend = PageToSendTo + VariablePlaceholder + MyVariable;&nbsp; &nbsp; &nbsp; xhttp.open("GET", UrlToSend, false);&nbsp; &nbsp; &nbsp; xhttp.send();&nbsp; &nbsp; &nbsp;});&nbsp; &nbsp;}并用await它来称呼它:&nbsp; document.getElementById('demo').innerHTML = 'test' + await savedNumberOfLessonInDay(number);或者,如果由于某种原因您不能使用await:&nbsp; savedNumberOfLessonInDay(number).then((response) => {&nbsp; &nbsp; &nbsp; document.getElementById('demo').innerHTML = 'test' + response;&nbsp; });

桃花长相依

尝试使用 async/await 这里是如何使用它。https://javascript.info/async-await

拉丁的传说

函数 savedNumberOfLessonInDay() 不会等待 ajax 完成。所以需要在回调函数xhttp.onreadystatechange中设置demo的html。在不改变你的实现太多的情况下,你可以简单地修改你的代码:function savedNumberOfLessonInDay(dayID){&nbsp;var xhttp = new XMLHttpRequest();&nbsp; xhttp.onreadystatechange = function() {&nbsp; &nbsp; &nbsp; if (this.readyState == 4 && this.status == 200) {&nbsp; &nbsp; &nbsp; &nbsp; document.getElementById('demo4').innerHTML = this.responseText; //Returns the right number&nbsp; &nbsp; &nbsp; &nbsp; document.getElementById('demo').innerHTML = 'test' + this.responseText;&nbsp; &nbsp; }&nbsp; };&nbsp; var PageToSendTo = "AJAX/countLessonInDay.php?";var MyVariable = dayID;var VariablePlaceholder = "GETDayID=";var UrlToSend = PageToSendTo + VariablePlaceholder + MyVariable;&nbsp; xhttp.open("GET", UrlToSend, false);&nbsp; xhttp.send();}然后只需调用该函数而不是尝试设置savedNumberOfLessonInDay(number);
打开App,查看更多内容
随时随地看视频慕课网APP