通过AJAX函数加载php

时间:2019-02-11 18:53:08

标签: javascript php html

这个想法基本上是能够以表格形式写出您的年龄,并且在提交您的年龄后,您可以加载一些内容。 (例如,您年龄段的某人可能喜欢的相关音乐)。在我开始工作之前,我想看看我是否可以回应提交的年龄。而且我在使用xhttp请求时遇到了问题。

我尝试在GET和POST方法之间进行更改,我尝试切换form属性,因此我给它一个“ onsubmit”而不是“ action”。我到目前为止尝试过的解决方案要么什么都不做,要么显示php“未定义索引”错误。我遇到的另一个问题是错误出现了一秒钟然后消失了。

第1步-index.php:

<nav class="navbar navbar-expand-sm bg-dark navbar-dark sticky-top">
  <ul class="navbar-nav">
    <li class="nav-item">
      <a class="nav-link" href="javascript:loadLiving();">Living</a>
    </li>
  </ul>
</nav>

<div id="body">    </div>

第2步-脚本:

function loadLiving() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("body").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "living.php", true);
  xhttp.send();
}

第3步-living.php:

    <div class="list-group">
      <a href="#houseform" class="list-group-item" data-toggle="collapse">Buying a house</a>
      <div id="houseform" class="collapse">
          <form action="javascript: calculateHousing();" method="POST">
          <br>
          <input type="text" name="age" placeholder="What is your Age"/>
          <button name="submit" type="submit">SUBMIT</button>
          </form>
          <br>
      </div>


第4步-scripts.js:

function calculateHousing() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("body").innerHTML = this.responseText;
    }
  };
  xhttp.open("POST", "getHousing.php", true);
  xhttp.send();
}

来自getHousing.php:

<?php

if(isset($_POST['submit'])) {
echo $_POST["age"];
}
  ?>

希望看到在“ body” div中回显的年龄。但我得到一个空白,窗体和可折叠消失,但没有加载任何内容。

0 个答案:

没有答案