Print a div with data from ajax or jquery.get()

前端 未结 3 1491
耶瑟儿~
耶瑟儿~ 2021-01-15 17:56

I have a div:

that gets populated by JQuery using innerHTML with strings from client side jav

相关标签:
3条回答
  • 2021-01-15 18:15

    Go this way

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

    or

    $('#contract').append(
        $('<pre>').text(
            JSON.stringify(data, null, '  ')
        )
    )
    
    0 讨论(0)
  • 2021-01-15 18:19

    you can not print a tag directly .But this trick can help:

    <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>
    
    0 讨论(0)
  • 2021-01-15 18:22

    Try using a hidden 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/

    0 讨论(0)
提交回复
热议问题