使用ajax或jquery.get()

时间:2015-12-10 16:12:47

标签: javascript jquery html ajax printing

我有一个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" 打印出来。如果我不删除$.get,则不会打印。我尝试使用$.ajax代替$.get,但这并不能解决问题。我尝试使用CSS解决方案here,但这会混淆来自服务器端的数据(HTML),因为它已经嵌入了CSS分页媒体。因此,我不想使用CSS解决方案。

div包含从服务器端获取的数据时,有人可以建议我使用JQuery打印div的好方法吗?

3 个答案:

答案 0 :(得分:0)

走这条路

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

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

答案 1 :(得分:0)

尝试使用隐藏的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 :(得分:-1)

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

<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>
相关问题