微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript:打印通过ajax接收的文本

这就是我想要做的:

>用户点击打印按钮;
>这调用函数,它执行ajax调用获取要打印的文本;
>将打开一个新窗口,并将文本写入此窗口.

窗口和打印的处理方式如下:

 my_text = "hello";

 newWin= window.open();
 newWin.document.write(my_text);
 newWin.document.close();
 newWin.focus();
 newWin.print();
 newWin.close();

这很好用.我的问题是如何获取my_text.我试图将上面的代码放在ajax调用中:

$.ajax({
        type: "GET", url: the_url, data: {},
        success: function(data){
             newWin= window.open();
             newWin.document.write(data);
             newWin.document.close();
             newWin.focus();
             newWin.print();
             newWin.close();
        }
        ,error: function() {
        } 
     }); 

但是,这会导致新窗口被视为弹出窗口,并被弹出窗口阻止程序捕获.如果我选择查看弹出消息,那么它已正确填写文本.我先尝试打开窗口,但后来没有任何内容写入.

解决方法:

尝试移动线:

newWin = window.open();

在$.ajax(…)调用之前.您的窗口将立即打开,当ajax调用完成时,您的成功处理程序应该能够写入它.你会得到类似的东西:

var newWin = window.open();
$.ajax({
    type: "GET", url: the_url, data: {},
    success: function(data){
        newWin.document.write(data);
        newWin.document.close();
        newWin.focus();
        newWin.print();
        newWin.close();
    }
    ,error: function() {
    }
});

使用setTimeout的简化版本用于“概念证明”目的.

<html>
<head>
<script>
function openWindow() {
  var win = window.open("about:blank", "", "width=800,height=600");
  setTimeout(function() {
    win.document.write("Hello World!");
    win.document.close();
  }, 1000)
}
</script>
</head>
<body>

<button type="button" onclick="openWindow()">Click me</button>

</body>
</html>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐