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

时间:2015-04-07 23:00:51

标签: javascript php jquery html

我想将另一个(news.html)页面的文本预览加载到我的主页中,然后加载到div(id =“news_pre”)。我目前正在使用getElementById来加载news.html页面并且它正在运行。但是,我想只使用最大字符数(150)预览news.html页面。我知道它可以在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>

1 个答案:

答案 0 :(得分:0)

我建议,如果你想操纵来自另一个页面的数据,而不是使用object标签,你使用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