从单独的html文件预览Javascript文本

Javascript text preview from separate html file

本文关键字:Javascript 文本 文件 单独 html      更新时间:2023-09-26

我想将另一个(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教程