0

我正在尝试发出警报消息,以显示在将用户名从帖子表单提交到带有 json 的 php 文件后是否使用了用户名。我制作了这个 javascript 文件,并承诺获取获取 json 的请求 -

window.onload = function(){

    function get(url) {
        return new Promise((resolve, reject) => {
          const xhr = new XMLHttpRequest();
          xhr.open("GET", url);
          xhr.onload = () => resolve(xhr.responseText);
          xhr.onerror = () => reject(xhr.statusText);
          xhr.send();
        });
      }

    document.getElementById('register').addEventListener('submit', () => {
            let promise = get('/controllers/add-user.php').then((name) => {
            console.log(name);
        });
    });
}

我的问题是承诺是在加载带有 json 的 php 文件之前执行的,所以我在控制台中收到这些错误

[Thu Aug 16 12:16:22 2018] PHP Notice:  Undefined index: password in /home/orpheus/Practice_dev/imagePoster/controllers/add-user.php on line 5
[Thu Aug 16 12:16:22 2018] PHP Notice:  Undefined variable: app in /home/orpheus/Practice_dev/imagePoster/controllers/add-user.php on line 7
[Thu Aug 16 12:16:22 2018] PHP Fatal error:  Uncaught Error: Call to a member function nameTaken() on null in /home/orpheus/Practice_dev/imagePoster/controllers/add-user.php:7
Stack trace:
#0 {main}
  thrown in /home/orpheus/Practice_dev/imagePoster/controllers/add-user.php on line 7
[Thu Aug 16 12:16:22 2018] 127.0.0.1:44996 [500]: /controllers/add-user.php - Uncaught Error: Call to a member function nameTaken() on null in /home/orpheus/Practice_dev/imagePoster/controllers/add-user.php:7
Stack trace:
#0 {main}
  thrown in /home/orpheus/Practice_dev/imagePoster/controllers/add-user.php on line 7

php 文件正确加载并显示正确的 json。当我用我的承诺重定向回页面时,我的控制台被清除了。所以我想知道如何在加载 json 文件并重定向回我的主页('/')后向它发出一个 promise get 请求?

如果我无法对我的 php post 请求发出 get 请求,那么我该怎么做?我的表单发布到我的数据库和 php 文件已经在工作,如果不使用它会将名称提交到我的数据库,如果已经使用它会阻止它们。我想在我的 html 中显示用户名已经被使用,如果它被使用,我不确定我的方法是否正确。我会很感激任何帮助。

4

1 回答 1

0

所以我想知道如何在加载 json 文件并重定向回我的主页('/')后向它发出一个 promise get 请求?

您必须运行从您的主页发出该请求的 JavaScript。

当您离开该页面时,您无法从上一页执行此操作。运行 XMLHttpRequest 请求的 JS 环境将被破坏。

于 2018-08-16T19:16:30.407 回答