简体   繁体   English

我可以用等效的 fetch() 调用替换 jQuery.load() 单行代码吗?

[英]Can I replace a jQuery.load() one-liner with an equivalent fetch() call?

I have a page that uses the jQuery one liner我有一个使用 jQuery one liner 的页面

$('#id').load('/url');

to load a fragment into the DOM at a specific place.将片段加载到 DOM 的特定位置。

If I want to remove the dependency on jQuery, is there an easy alternative way to do this — possibly with the relatively new fetch() API?如果我想删除对 jQuery 的依赖,是否有一种简单的替代方法可以做到这一点——可能使用相对较新的 fetch() API?

Do it like so:这样做:

fetch('/url')
  .then(response => response.text())
  .then(value => {
    document.getElementById('id').innerHTML = value
  });

Almost a one liner:)几乎一个班轮:)

;(async () => {
    document.getElementById('id').innerHTML = await (await fetch('/url')).text();
})();

to put it to some practical use you'd have at least to check the response code, so I'd first refactor it like this要将其用于实际用途,您至少必须检查响应代码,所以我首先会像这样重构它

;(async () => {
    let res = await fetch('/url');
    if(res.ok){
        document.getElementById('id').innerHTML = await res.text();   
    }
    else { ... }
})();

error handling is still missing, but I'm sure you get the picture:)错误处理仍然缺失,但我相信你明白了:)

You can do like this:你可以这样做:

fetch('/method')
.then(response=> response.text())
.then(res => { document.getElementById('id').innerHTML = res; });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM