简体   繁体   中英

Javascript text preview from separate html file

I want to load a preview of text from another (news.html) page into my home page into a div (id="news_pre"). I am currently using getElementById to load the news.html page in and it is working. However I want to just make a preview of the news.html page with a maximum amount of characters (150). I know it can be done in php but I don't know how to use php and was wondering if there is a way to do it in javascript. Thanks, This is my code.

<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>

I would suggest, if you want to manipulate the data from another page, instead of using the object tag, that you use an AJAX request. If you want the frame-esque look you can always apply some border styles using 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> 

EDIT: If you need more information you can check out this XMLHttp Tutorial

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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