使用 html 表单的 target 属性,您可以发布表单数据,然后在 iframe 中显示 html-server-response。
form.setAttribute("target", "nameOfIframe");
使用 ecmascript fetch api 可以实现同样的功能(无需创建实际的 html 表单元素)吗?
最佳答案
使用 JavaScript/EcmaScript 更新 IFRAME 的内容相当简单,可以使用 srcdoc
来完成属性。
document.getElementById('fetchTarget').srcdoc = `<!DOCTYPE html><p>Hello World!</p>`;
<iframe id="fetchTarget">
</iframe>
您需要做的就是安排更新它,作为 fetch
调用处理的一部分:
fetch(`https://jsonplaceholder.typicode.com/posts/1`)
.then(response => {
console.log(response);
if (response.ok){
return response.text();
}
})
.then(text => {
document.getElementById('fetchTarget').srcdoc = text;
});
<iframe id="fetchTarget">
</iframe>
此 URL 并不是一个特别好的示例,因为它返回 JSON 而不是 HTML,但它并不真正影响结果。
关于javascript - 获取 API - 定位 Iframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50884838/