【问题标题】:Sending data from javascript to php to generate a pdf but doesn't work将数据从javascript发送到php以生成pdf但不起作用
【发布时间】:2018-11-25 23:37:23
【问题描述】:

我正在使用 JavaScript 从用户填写的表单中获取信息,然后将此数据发送到 PHP 并使用 FPDF 生成 PDF。问题是我希望浏览器要求用户保存 PDF 或在线查看但 我不知道怎么做。 PDF 正确生成,但仅当我将其直接保存到我指定的某个路径时。

问题是你们如何将数据从 JavaScript 发送到 PHP 以生成 PDF 文件,然后浏览器要求用户打开或下载,或者我如何创建一个用户可以检索此 PDF 的功能。

JavaScript:

function senddata() {//this activates when i push a button not a submit
    var peticion = new XMLHttpRequest();
    peticion.open('POST', 'generatepdf.php');
    var nueva2 = {};
    var key;

    for (i = 0; i < 6; i++) {
        key = document.forms[0].elements[i].id;
        nueva2[key] = document.forms[0].elements[i].value;
    }//here i take my data from the form and make an object

    var json = JSON.stringify(nueva2);//here i tranform my object to json string so i can send it to my php

    var parametros = "json_string=" + json;//here I do this so later I can easily transform the $_POST to an array in the form json_decode($_POST["json_string"],true); 

    peticion.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    peticion.send(parametros);//it sends ok
}

带有 FPDF 类和东西的 PHP

<?php

require('fpdf/fpdf.php');
require('functions.php');

if($_SERVER['REQUEST_METHOD']=='POST'){

    $datos=json_decode($_POST["json_string"],true); //here i have my data in an array format so i can use the parameters to fill my pdf fields

    //...lots of pdf things here...//

 $pdf->Output('F',"pdfs/Cotizacion ".$datos["nombres"]." ".$datos["apellidos"].".pdf");//this works but never ask the user
 //$pdf->Output('D',"pdfs/Cotizacion ".$datos["nombres"]." ".$datos["apellidos"].".pdf");//this should force a dowload or send to the browser but doesnt work
 //$pdf->Output();//this should send to the browser but doesnt work
    }

【问题讨论】:

标签: javascript php ajax fpdf


【解决方案1】:

要在浏览器中查看内嵌 PDF,您应该改用 I 变量。查看完整文档here

另外,我认为同时以两种方法输出文件是行不通的。可能会互相冲突。最好的方法是测试每种方法,如果它确实相互冲突,只需简单地添加一个条件让用户决定他/她是要下载还是在浏览器中查看它。希望这会有所帮助。

【讨论】:

  • 感谢您的回答,我没有使用 2 种输出方法只是写了这种方式来显示我的不同尝试,只是尝试使用 'I' 但不起作用。无论如何编辑了我的原始帖子以进行澄清
猜你喜欢
  • 2013-04-17
  • 2015-11-03
  • 2015-12-25
  • 1970-01-01
  • 2010-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多