gpt4 book ai didi

来自单独 html 文件的 Javascript 文本预览

转载 作者:行者123 更新时间:2023-11-28 07:27:16 28 4
gpt4 key购买 nike

我想将另一个 (news.html) 页面的文本预览加载到我的主页的 div (id="news_pre") 中。我目前正在使用 getElementById 加载 news.html 页面并且它正在工作。不过,我只想预览 news.html 页面的最大字符数 (150)。我知道它可以在 php 中完成,但我不知道如何使用 php,并且想知道是否有办法在 javascript 中完成它。谢谢,这是我的代码。

<div id="news_pre">
<p> news </p>
<script>
function news(){
document.getElementById("news_pre").innerHTML='<object width="100%" height="100%" type="text/html" data="news.html" ></object>';

}
</script>
</div>

最佳答案

如果您想操作另一个页面的数据,我建议您使用 AJAX 请求,而不是使用对象标记。如果您想要框架式的外观,您可以随时使用 css 应用一些边框样式。

<!DOCTYPE html> 
<html>

<script>
window.onload = function() {
// when the window loads
var xhr; (XMLHttpRequest) ? xhr= new XMLHttpRequest() : xhr= new ActiveXObject("Microsoft.XMLHTTP");
//check if XMLHttpRequest is available in browser, if IE use ActiveXObject instead.

xhr.onload = function() {
// when loading the request do the following
if(xhr.readyState === 4 && xhr.status === 200) {
// if the load is completed successfully
var preview = xhr.responseText;
// Get news.html and place it in the variable preview
preview = preview.substring(0, 149);
// Keep the first 150 characters from news.html in the variable preview
document.getElementById("content").innerHTML = preview;
// Place the content in preview into the element with id "content"

}
}
xhr.open("GET", "news.html", true);
//This tells the request where to go
xhr.send();
//This sends the request to get news.html
}
</script>


<h1> News Preview is Below! </h1>
<p>
<section id="content"></section> <br>
</html>

编辑:如果您需要更多信息,可以查看此 XMLHttp Tutorial

关于来自单独 html 文件的 Javascript 文本预览,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29502883/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com