【发布时间】: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
}
【问题讨论】:
-
我不确定你的意思,但你可能想看看内容处置:developer.mozilla.org/en-US/docs/Web/HTTP/Headers/…
标签: javascript php ajax fpdf