【问题标题】:Print a div with data from ajax or jquery.get()使用来自 ajax 或 jquery.get() 的数据打印一个 div
【发布时间】:2015-12-10 16:12:47
【问题描述】:

我有一个 div:

<div id="contract"></div>

由 JQuery 使用 innerHTML 填充,其中包含来自客户端 javascript 的字符串和从我的服务器获取的数据 (HTML):

$('#submit').click(function () {       
    document.getElementById('contract').innerHTML = 'foobar';    
    var profile = $('#profile').val();
    var query = {
        'profile': profile
    };
    $.get('/foo/profileViewer', query, function (data) {
        var result = $.parseJSON(data);            
        document.getElementById('contract').innerHTML += result ;  //$('#contract').html(result); doesn't work either         
    })
});

我只想打印contract div

我尝试了建议 herehere 的 JQuery 答案,并且所有答案都指向 div 已经 包含 HTML 中的文本开头而不是从服务器获得的内容的答案.奇怪的是,如果我删除 $.get 并实施提供的答案之一,"foobar" 确实 会被打印出来。如果我不删除 $.getnothing 会被打印出来。我尝试使用 $.ajax 而不是 $.get 但这并不能解决问题。我尝试使用 CSS 解决方案 here 但这会弄乱来自服务器端的数据 (HTML),因为它已经嵌入了 CSS 分页媒体。因此,我不想使用 CSS 解决方案。

div 包含从服务器端获取的数据时,谁能建议我使用JQuery 打印div 的好方法?

【问题讨论】:

  • 向我们展示您来自/foo/profileViewer的代码
  • 打印是什么意思?
  • 打印我的意思是实际上让浏览器弹出一个打印窗口,打印我想要的网页部分

标签: javascript jquery html ajax printing


【解决方案1】:

尝试使用隐藏的 iframe:

$('#submit').click(function (e) {  
    e.preventDefault();     
    $('#contract').empty();    
    var profile = $('#profile').val();
    var query = {
        profile: profile
    };
    $.get('/foo/profileViewer', query, function (data) {            
        $('body').append('<iframe id="printf" style="display:none;" name="printf"></iframe>');
        $('#printf').contents().find('body').append(data);
         window.frames["printf"].focus();
         window.frames["printf"].print();       
    })
});

https://jsfiddle.net/njezoem5/

【讨论】:

    【解决方案2】:

    往这边走

    $('#contract').text(JSON.stringify(data));
    

    $('#contract').append(
        $('<pre>').text(
            JSON.stringify(data, null, '  ')
        )
    )
    

    【讨论】:

    • 我之前也尝试过$('#contract').html(result);,但它对我不起作用。因此,我转移到document.getElementById('contract').innerHTML += result ;
    【解决方案3】:

    你不能直接打印标签。但是这个技巧可以帮助:

    <script language="javascript" type="text/javascript">
        function printDiv(divID) {
            //Get the HTML of div
            var divElements = document.getElementById(divID).innerHTML;
            //Get the HTML of whole page
            var oldPage = document.body.innerHTML;
    
            //Reset the page's HTML with div's HTML only
            document.body.innerHTML = 
              "<html><head><title></title></head><body>" + 
              divElements + "</body>";
    
            //Print Page
            window.print();
    
            //Restore orignal HTML
            document.body.innerHTML = oldPage;
    
    
        }
    </script>
    

    【讨论】:

    • 它搞砸了页面的所有动态功能:按钮等
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-03
    相关资源
    最近更新 更多