Delay window.print () until the page loads into an ajax request to avoid a blank print screen?

What I'm trying to do with this code is to make an ajax request for what generates barcodes and returns them for printing. When I make a request, it generates everything correctly, but the print window is empty. If I cancel the print window, the correct barcodes will be printed in the base window. I suspect that I need to defer .print () until the child window is fully loaded, but the solution eludes me. Thanks in advance for your help!

var barcode = $.ajax({
     url: "barcode.php",
     method: "POST",
     data: {
            name : name,
            text : text,
            number : numLines
            },
});
var printText;
barcode.done(function( jqXHR, textStatus ) {
    printText = jqXHR;
    var WindowObject = window.open();
    WindowObject.document.writeln(printText);
    WindowObject.focus();
    WindowObject.print();

});

All this is wrapped in $ (document) .ready (function () {});

+4
source share
2 answers

: , , , , , , ( ) .

. URL- window.open, , script, window.print, . , , , , "barcode.php" GET, , , .

// Assumes parameters provided are safe to use in a url.
window.open('barcode.php?name=' + name + '&text=' + text + '&number=' + number');

, "barcode.php", script:

document.onload = function() {
    window.focus();
    window.print();
    window.close();
};

, , , , ( , ) load onload.


: , . , , .

, :

  • window.open
  • write ( writeln) , .
  • write a <script>, :
    • , document.readyState; , . :
    • setTimeout, document.readyState, . ( , .)
    • , load onload, , .

, :

var WindowObject = window.open();
WindowObject.document.write('<img src="http://i.imgur.com/Jvh1OQm.jpg" />'); // This is your content to be printed
WindowObject.document.write('<script>(' + (function() {
    function checkReadyState() {
        if (document.readyState === 'complete') {
            window.focus();
            window.print();
            window.close();
        } else {
            setTimeout(checkReadyState, 200); // May need to change interval
        }
    }

    checkReadyState();
}) + ')();</sc' + 'ript>');

, , , . , , -.

+2

WindowObject.onload = function () { ... }; :

barcode.done(function( jqXHR, textStatus ) {
    printText = jqXHR;
    var WindowObject = window.open();
    WindowObject.onload = function () {
        WindowObject.document.writeln(printText);
        WindowObject.focus();
        WindowObject.print();
    };
});
0

All Articles