问题
I am currently using JS and Ajax requests to edit some HTML tags depending on certain controller method results. This is all working fine until I want to Generate a PDF, I have been doing some research and have found some "solutions" to this using the javascript_delay and window-status but was unsuccessful.
Following the guide of wkhtmltopdf I am using the wicked_pdf_javascript_include_tag to load the JS file and this is being written and saved, but I dont know if the Javascript is being executed as the "visual" part is generated in the AJAX part of the .js file which is not being shown in the PDF.
The controller is returning a complete HTML that I want to visualise in a HTML container:
$.ajax({
url: "/monitor/device/"+widget.property.device_sensor,
type: 'GET',
dataType: 'html'
}).done(function (datos) {
$container.html(datos);
}).always(function () {
redBorder.widgets.util.reloadDone($container.parents('.widget'));
});
This is using the GEM wkhtmltopdf in Rails
How can I know that the JS is being executed and if it is being executed and the issue is with the AJAX call how could this be fixed?
回答1:
During rendering with wicked-pdf
the page is saved to a temporary file on disk and opened via file://
protocol. The result is that page knows nothing about your server address, and even if it did - it will have different origin, which by default prevents ajax calls (need to setup CORS to bypass that).
For pdfs it's better to get rid of ajax calls, because obviously there'll be no user interaction, and render all necessary data in view.
回答2:
Try something like this:
var httpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
httpRequest.open('GET', url);
httpRequest.withCredentials = true;
httpRequest.responseType = 'text';
httpRequest.onreadystatechange = function(){
if (httpRequest.readyState === 4) {
/do stuff
}
};
httpRequest.send();
This replaces the ajax call with pure javascript. Hope this was of help, Pedro.
来源:https://stackoverflow.com/questions/59858026/wicked-pdf-not-making-ajax-js-calls