【问题标题】:Equivalent to $.load without jQuery相当于没有 jQuery 的 $.load
【发布时间】:2016-11-03 02:30:09
【问题描述】:

我想在单击按钮时将一些 Jade 内容加载到某个 div 中。我已经找到了如何使用 jquery 来做到这一点,上面有几个帖子,基本上我想要做的是

$('#div').load('/somePage');

但是,我无法在我的项目中使用 jQuery。 vanilla javascript中是否有等效功能?

【问题讨论】:

  • "Vanilla JavaScript" 没有任何类似 ajax 的规定。浏览器具有旧的 XMLHttpRequest API,而较新的浏览器支持 fetch() API。
  • 你可以在youmightnotneedjquery.com找到类似的东西
  • 另见fetch API。

标签: javascript jquery node.js express pug


【解决方案1】:

我认为您可以通过以下方式做到这一点;

var request = new XMLHttpRequest();

request.open('GET', '/somepage', true);

request.onload = function() {
  if (request.status >= 200 && request.status < 400) {
    var resp = request.responseText;

    document.querySelector('#div').innerHTML = resp;
  }
};

request.send();

顺便说一句,您也可以使用 fetch API 来做到这一点。

fetch('/somepage')
  .then(function(response) {
    return response.text();
  })
  .then(function(body) {
    document.querySelector('#div').innerHTML = body;
  });

顺便说一句,您可以阅读 this blog post 了解有关 fetch API 的一些知识。

【讨论】:

  • 注意:任何 IE 版本、最新的 Safari 和最新的 Firefox 都不支持 fetch。 developer.mozilla.org/en-US/docs/Web/API/…
  • @JonathanLaliberte 我不认为 ReadableStream 对于这种情况是必要的。所以我想说所有现代浏览器(除了 IE)都支持它。除此之外,还有一个用于不支持 Fetch 的浏览器的 polyfill。 github.com/github/fetch
  • 很好的开始,但是我们缺少可以指定返回页面子集的部分。我在separate thread 中找到了该位的开始。
  • 我得到文件未定义
  • @Normajean 你能用一些你正在使用的代码 sn-ps 发布一个新问题吗?
【解决方案2】:

当我试图解决同样的问题时,我做了这个基于Ali BARIN's answer,看起来效果很好,但版本更明确,添加了init信息,并且有一些逻辑可以使用@ 987654323@ 而不是 querySelector

/*
 * Replicates the functionality of jQuery's `load` function, 
 * used to load some HTML from another file into the current one.
 * 
 * Based on this Stack Overflow answer:
 * https://stackoverflow.com/a/38132775/3626537
 * And `fetch` documentation:
 * https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
 * 
 * @param {string} parentElementId - The ID of the DOM element to load into
 * @param {string} htmlFilePath - The path of the HTML file to load
 */
const loadHtml = function(parentElementId, filePath) {
    const init = {
        method : "GET",
        headers : { "Content-Type" : "text/html" },
        mode : "cors",
        cache : "default"
    };
    const req = new Request(filePath, init);
    fetch(req)
        .then(function(response) {
            return response.text();
        })
        .then(function(body) {
            // Replace `#` char in case the function gets called `querySelector` or jQuery style
            if (parentElementId.startsWith("#")) {
                parentElementId.replace("#", "");
            }
            document.getElementById(parentElementId).innerHTML = body;

        });
};

【讨论】:

  • 如何从服务器端访问 document.getElementById(parentElementId).innerHTML = body 中的文档?我得到文件未定义..
【解决方案3】:

你可以这样做,但有一些事情你必须注意。

const getData = (url) => {
  return new Promise((resolve, reject) => {
    let request = new XMLHttpRequest();
    request.onload = function () {
      if (this.readyState === 4 && this.status === 200) {
        resolve(this.responseText);
      } else {
        reject(this.responseText);
      }
    };
    request.open("get", url, true);
    request.send();
  });
};

getData("Your URL")
  .then((resolve) => {
    console.log(resolve);
  })
  .catch((reject) => {
    console.error(reject);
  });

我想让你注意的是,如果你把 URL 放到一个页面上,它会从&lt;html&gt;&lt;/html&gt; 作为字符串返回,我想没有办法像这样分开它jQuery 中的方法.load()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多