繁体   English   中英

通过单击按钮使用JavaScript从页面打印另一页面

[英]Print another page using JavaScript from a page by clicking on a button

我有一个带有按钮的html页面,该按钮允许使用以下代码打印特定内容:

<div class="below_movie_left" id="printableArea">
My printing contents
</div>

<input type="button"  class="submit_button" onclick="printDiv('printableArea')" value="Print" style="float:right;" />

<script>
function printDiv(divName) {
     var printContents = document.getElementById(divName).innerHTML;
     var originalContents = document.body.innerHTML;

     document.body.innerHTML = printContents;

     window.print();

     document.body.innerHTML = originalContents;
}
</script>

好吧,它可以完美地打印我的特定内容。 但是,现在我想使用此按钮打印另一页。 另一个页面名称是finalprinting.php

所以现在我想要,当我按下此“ 打印”按钮时,它应该是print finalprinting.php页面,而不是页面的现有内容。

因为我不太了解jQuery,所以我会尝试在没有它的情况下进行操作

function printDiv(divName){
    var xmlhttp = new XMLHttpRequest();
    var originalContents = document.body.innerHTML;
    xmlhttp.open('GET', '/finalprinting.php', false);
    xmlhttp.send(null);
    if(xmlhttp.status == 200) {
        document.body.innerHTML = xmlhttp.responseText;
        window.print();
        document.body.innerHTML = originalContents;;
    }
}

您需要使用AJAX。

<input type="button" id="loadpage" value="Print">
<script>

document.getElementById( "loadpage" ).addEventListener( "click", function(){
    var request = new XMLHttpRequest();
    request.open("GET", "finalprinting.php", true);

    request.onload = function(){
        if (request.status >= 200 && request.status < 400){
            // We got the data, now we can set the body's innerhtml
            document.body.innerHTML = request.responseText;
        } else {
            // We reached our target server, but it returned an error
        }
    };

    request.onerror = function() {
        // There was a connection error of some sort
    };

    request.send();
});
</script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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