Javascript 如何将AJAX responseText传递到变量中

Javascript 如何将AJAX responseText传递到变量中,javascript,ajax,Javascript,Ajax,我想知道如何将AJAX responseText传递到变量中?我想在程序的另一部分中使用它。代码“document.getElementById(“showData”).innerHTML=xhttp.responseText;”可以正确显示返回字符串,但我不能使用变量来接收它 <?PHP $currHr=date('H')-1; ?> <form action=""> <Select name="SelTime" onchange="rainSum(this

我想知道如何将AJAX responseText传递到变量中?我想在程序的另一部分中使用它。代码“document.getElementById(“showData”).innerHTML=xhttp.responseText;”可以正确显示返回字符串,但我不能使用变量来接收它

<?PHP
$currHr=date('H')-1;
?>

<form action=""> 

<Select name="SelTime" onchange="rainSum(this.value)">
<?php
if ($currHr>0){
for ($i=$currHr; $i>=0; $i--)
{
    echo "<option value=".$i.">".$i.":00";
    echo " - ";
    echo $i.":59</option><br>";
}   
}else {
    for ($i=23; $i>=0; $i--)
{
    echo "<option value=".$i.">".$i.":00";
    echo " - ";
    echo $i.":59</option><br>";
}   
}
?>
</Select>
</form>

<p id="showData">Let AJAX change this text.</p>

<script>

function rainSum(str) 
{
  var xhttp = new XMLHttpRequest();

  xhttp.onreadystatechange = function () 
  {

 if (xhttp.readyState === 4 && xhttp.status === 200)
 {
   document.getElementById("showData").innerHTML = xhttp.responseText;
   window.x=xhttp.responseText;
    }
  };

  xhttp.open("GET", "barD.php?SelTime="+str, true);
  xhttp.send();
}



document.write(window.x);</script>

让AJAX更改此文本

函数雨和(str) { var xhttp=newXMLHttpRequest(); xhttp.onreadystatechange=函数() { if(xhttp.readyState==4&&xhttp.status==200) { document.getElementById(“showData”).innerHTML=xhttp.responseText; window.x=xhttp.responseText; } }; open(“GET”、“barD.php?SelTime=“+str,true”); xhttp.send(); } document.write(window.x);
如果您的意思是x变量应该包含响应数据,那么它已经包含了响应,因为它是一个全局变量

您不需要window.x,只需在函数外部声明一个变量即可

像这样

var ResponseTXT='';

    function rainSum(str) 
    {
      var xhttp = new XMLHttpRequest();

      xhttp.onreadystatechange = function () 
      {

     if (xhttp.readyState === 4 && xhttp.status === 200)
     {
       document.getElementById("showData").innerHTML = xhttp.responseText;
       ResponseTXT=xhttp.responseText;
        }
      };

      xhttp.open("GET", "barD.php?SelTime="+str, true);
      xhttp.send();
    }

您以异步状态引导,在异步场景中,您不能以传统方式将值分配给变量,因为您必须等待函数返回其结果,这可以通过多种方式完成,其中一种方式是执行示例中的异步函数,然后使用,使用或调用异步函数并等待其结果,然后使用它

async function rainSum(str) {
    const response = await fetch(`barD.php?SelTime=${str}`);

    return await response.json();
}

// subscribe to the asynchronous function
rainSum("some string").then(response => console.log(response));
一些相关链接


花点时间了解同步函数和异步函数之间的区别,以及这些情况下的javascript方法,在javascript中使用异步函数是非常常见的,熟悉文档中的概念是明智的。write(window.x),我只是用它做一个测试,同时,您也可以使用jquery尝试ajax,它使用
传递所有变量。serialize
我相信这个问题与您提出的问题有一定的关系,请尝试一下
async function rainSum(str) {
    const response = await fetch(`barD.php?SelTime=${str}`);

    return await response.json();
}

// subscribe to the asynchronous function
rainSum("some string").then(response => console.log(response));