【问题标题】:AJAX + Promises: Chaining AJAX calls not workingAJAX + Promises:链接 AJAX 调用不起作用
【发布时间】:2018-07-05 05:01:30
【问题描述】:

我正在尝试向 php 页面 (delete_post.ajax.php) 发出 POST(技术上是 DELETE)请求,该页面从我的 AJAX 调用中获取数据,并使用它来删除我的数据库中的项目。之后,我希望我的 AJAX 向另一个页面 (api/blog.php) 发出 GET 请求,该页面在数据库中查询该表中的其余项目。

到目前为止,我能够 DELETE 数据库中的项目,但是当链接到 .then() 时,它并没有像我期望的那样链接。

如果我访问...api/blog.php,页面会按预期返回有效的JSON

JS AJAX

const deletePostBtn = document.querySelectorAll('button[name="delete_post"]');

// GET REQUEST TO RETRIEVE EVERY POST
const get = (url) => {
  return new Promise((resolve, reject) => {
    const xhttp = new XMLHttpRequest();

    xhttp.open('GET', url, true);

    xhttp.onload = () => {
      if (xhttp.status == 200) {
        resolve(JSON.parse(xhttp.response));
      } else {
        reject(xhttp.statusText);
      }
    };

    xhttp.onerror = () => {
      reject(xhttp.statusText);
    };

    xhttp.send();
  });
}

// DELETE SPECIFIC POST
const deletePostPromise = (url, postID) => {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();

    xhr.open('POST', url, true);

    xhr.onload = () => {
      if (xhr.status == 200) {
        console.log('if (xhr.status == 200)');
      } else {
        reject(xhr.statusText);
      }
    };

    xhr.onerror = () => {
      reject(xhr.statusText);
    };

    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    // console.log(`About to SEND ${postID}`);
    xhr.send(postID);
    // console.log(`Just SENT ${postID}`);
  });
}

// MAKING THE CALL TO DELETE THE POST
if (deletePostBtn) {
  for (let i = 0; i < deletePostBtn.length; i++) {
    deletePostBtn[i].addEventListener('click', e => {
      e.preventDefault();

      const displayPostSection = document.querySelector('.col-8.pt-4');
      const postID = document.querySelectorAll('#delete-post-id');

      deletePostPromise('http://localhost/mouthblog/ajax/delete_post.ajax.php', `id=${postID[i].value}`)
        .then(() => {
          console.log('DOES NOT MAKE IT TO THIS console.log');
        })
        .then(() => {
          get('http://localhost/mouthblog/api/blog.php')
            .then(data => {
              console.log(data);
            })
            .catch(error => {
              console.log(error);
            });
        });
    });
  }
}

delete_post.ajax.php(页面提交删除帖子)

<?php

  include('../includes/db/connection.php');
  include('../includes/db/delete/delete_post.query.php');

  $delete_post = new DeletePost($_POST['id']);

include('../includes/db/delete/delete_post.query.php');

<?php

class DeletePost extends Connection {
  public function __construct($id) {
    $this->connect();

    $sql = "DELETE FROM `posts`
            WHERE `id`=:id";
    $query = $this->connect()->prepare($sql);
    $result = $query->execute(
      [
        ':id' => htmlentities($id, ENT_QUOTES, 'ISO-8859-15'),
      ]
    );
  }
}

/api/blog.php(这是我的JSON的来源,返回所有帖子数据)

<?php

  include('../includes/db/connection.php');
  include('../includes/db/read/blog_roll.query.php');
  $get_data = new BlogRoll;

include('../includes/db/read/blog_roll.query.php');

<?php

class BlogRoll extends Connection {
  public function __construct() {
    $this->connect();

    $sql    = "SELECT `id`, `user_id`, `user_name`, `content`, `date_created`
               FROM `posts`
               ORDER BY `date_created` DESC";
    $query  = $this->connect()->prepare($sql);
    $result = $query->execute();

    if ($result) {
      $returnArray = [];

      while ($row = $query->fetch(PDO::FETCH_OBJ)) {
        array_push($returnArray, $row);
      }

      header('Content-Type: application/json;charset=UTF-8');
      exit(json_encode($returnArray));
    }
  }
}

【问题讨论】:

    标签: javascript php ajax promise


    【解决方案1】:

    对于deletePostPromise:在xhr.onerror 内部,你调用reject(),但你从不调用resolve()(我希望你在xhr.onload 内部调用)。

    then 只有在你解决或拒绝承诺时才会做某事。由于没有错误,所以不会被拒绝,也没有条件可以解决。

    (您确实为get 解决了它)。

    【讨论】:

    • 浏览MOZ DEV 文档,我认为我并不完全理解resolve()。在我的get 通话中,您可以看到我正在给它xhr.response。现在在我的POST 中,我没有传递任何东西,它正在工作。我是否也应该在我的POST 中传递任何内容,或者如果我将其留空也可以吗?
    • 您传递给resolve 的内容将传递给您传递给then 的函数。如果您想将数据从 Promise 中传递出去,这是通常的做法。您的代码期望那里没有任何数据。
    【解决方案2】:

    简要阅读代码,我在 deletePostPromise() 中没有看到任何 resolve() 函数。因此,只有当您在 REST 调用中出现错误时,您才会从 Promise 返回。

    【讨论】:

      猜你喜欢
      • 2010-09-30
      • 1970-01-01
      • 2013-05-06
      • 2010-09-26
      • 2013-09-06
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      相关资源
      最近更新 更多