Javascript 响应中的 XMLHTTPRequest .classList

Javascript XMLHTTPRequest .classList in response

如何检查从 XMLHTTPRequest 收到的响应是否有特定的 class?

async function swipeAction(currentElementObj) {
  var cardId = currentElementObj.getAttribute("value");
  var dataString = {'card': cardId};
  let response = await new Promise(resolve => {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "processes/explore.php", true);
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.send(JSON.stringify(dataString));
    xhr.onreadystatechange = function() {
      if(xhr.readyState == 4 && xhr.status == 200) {

        // I WANT TO CHECK SOMETHING LIKE THIS
        if(xhr.response.getElementById("matched").classList.contains('matched')) 
          alert(xhr.response.getElementById("matched").classList);

      }
    }
  });
}

在收到的响应中,我想检查 ID 为 matched 的元素是否具有 class 名称 matched。但是,上面的代码不起作用。这里正确的方法应该是什么?

如果您期望来自服务器的纯 text/html 响应,那么处理它可能如下所示:

async function swipeAction(currentElementObj) {
  var cardId = currentElementObj.getAttribute("value");
  var dataString = { card: cardId };
  let response = await new Promise((resolve, reject) => {
    try {
      var xhr = new XMLHttpRequest();
      xhr.open("POST", "processes/explore.php", true);
      xhr.setRequestHeader("Content-Type", "application/json");

      // add responseType = "document" for response to be parsed into DOM
      xhr.responseType = "document";
      // override response mime type (in case your server sends text/plain)
      xhr.overrideMimeType("text/html");

      xhr.send(JSON.stringify(dataString));
      xhr.onreadystatechange = function () {
        // check for non-empty responseXML property
        if (xhr.readyState == 4 && xhr.status == 200 && xhr.responseXML) {
          const matched = xhr.responseXML.getElementById("matched");

          if (!matched) return reject("Element not found in response");

          if (matched) {
            alert(matched.classList.contains("matched"));
            resolve(true);
          }
        } else {
          return reject("Incompatible response format");
        }
      };
    } catch (e) {
      reject(e.toString());
    }
  });
}