本文介绍了使用 XHR 更改 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如问题中如何使下面给出的代码在发出请求和加载页面内容后更改浏览器中的 URL?我自己不知道怎么做,我已经尝试了好几天了.

As in the question how to make the code given below change the URL in your browser after the request is made and after loading the content of the page?I don't know how to do it myself, I've been trying to do it for days.

如果可能,如何使从新页面加载的 JS 脚本(在请求之后)工作(innerHTML 不会解释为脚本的结果).

If possible, how to make JS scripts loaded from a new page (after the request) work (innerHTML does not interpret as a result of scripts).

document.addEventListener('click', function(event) {
  if (event.target.tagName !== "A" || !event.target.href) return;
    document.body.style.opacity = 0;
  event.preventDefault();
  document.body.addEventListener("transitionend", function() {
  var res = new XMLHttpRequest();
  res.addEventListener("load", function() {
       if (res.status != 200) {
 console.log(`Error ${res.status}: ${res.statusText}`);
  } else {
    document.querySelector('html').innerHTML =
      this.response;
  }
  });
  res.open("GET", event.target.href);
  res.send();
});
});

如果需要更多说明,请在下方评论.

If more clarification is needed, please comment below.

推荐答案

实际上,您可以在 AJAX 回调中更改整个页面.准备后端代码以使用文档中包含的 DTD 进行响应,并混淆所有结束脚本标签,例如..然后,在回调中,这样做:

Actually, you can change the entire page in the AJAX callback. Prepare the back-end code to response with the DTD included in the document, and obfuscate all the ending script tags, ex. <\/script>. Then, in the callback, do this:

else {
    document.write(res.responseText);
}

就是这样.但是,这违反了所有标准和良好做法,请勿使用它.

That's it. But, this is against all the standards and good practices, don't use it.

这篇关于使用 XHR 更改 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 05:49
查看更多