Wicked PDF not making AJAX / JS calls

て烟熏妆下的殇ゞ 提交于 2020-03-03 08:59:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!