【问题标题】:How to send a promise get request after a php json file has loaded?php json文件加载后如何发送promise get请求?
【发布时间】:2018-08-16 18:30:35
【问题描述】:

我正在尝试发出警报消息,以显示在将用户名从帖子表单提交到带有 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 中显示该用户名已经被使用,但我不确定我的方法是否正确。我会很感激任何帮助。

【问题讨论】:

    标签: javascript php json forms


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2010-10-31
      • 1970-01-01
      • 2020-11-13
      • 2018-03-30
      • 1970-01-01
      • 2019-08-15
      • 1970-01-01
      相关资源
      最近更新 更多