这个javascript函数采用JSON并将其格式化为XML。 数据是一个很长的XML字符串,我想允许用户下载。我正在尝试使用 ajax 将数据发布到 php 页面,wichi 将创建该文件,然后允许用户下载它。
json2xml(eval(data));
.JS
$.ajax({
type: 'POST',
url: 'download/functions.php',
data: xml2,
dataType: XML
});
我已经使用这个 PHP 函数写入文件,但我不确定现在如何将 js 变量发送到这个函数。
$data = $_POST['xml2'];
writetoxml($data, 'WF-XML'.$current. '.xml');
function writetoxml($stringData, $myFile) {
$current = date('m-d-Y-g-i-s');
$fh = fopen('download/'.$myFile, 'w') or die("can't open file");
fwrite($fh, $stringData);
fclose($fh);
download($file);
}
function downloadFile($file) {
if(!file)
{
// File doesn't exist, output error
die('file not found');
}
else
{
// Set headers
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/csv");
header("Content-Transfer-Encoding: binary");
// Read the file from disk
readfile($file);
exit;
}
}
这当前返回服务器 500 错误。
更新:
使用您提供的 jQuery AJAX 调用:
$.ajax({
type: 'POST',
url: 'download/yourphpscript.php',
data: { xml: xml2 },
dataType: XML
});
你的PHP看起来像这样:
<?php
$xml = $_POST['xml'];
// Not sure where you're trying to get $file from
writetoxml($xml, $file);
function writetoxml($stringData, $myFile) {
$current = date('m-d-Y-g-i-s');
$fh = fopen('download/'.$myFile, 'w') or die("can't open file");
fwrite($fh, $stringdata);
fclose($fh);
download($file);
}
function download($file)
{
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
}
?>
尝试将对象(在本例中为 { key: value }
传递到$.ajax
调用的数据属性中,以便可以通过键引用它。 在这种情况下,我们的密钥是xml
所以在PHP端,我们抓住$_POST['xml']
,这应该给你xml2的内容。
下载代码取自 readfile() 上的 PHP 文档。 但是,我仍然忍不住认为有更好的方法来实现这一目标。
我强烈建议不要允许用户有效地创建一个Web可访问的文件,其中包含他们在服务器上想要的任何内容。 如前所述,澄清您的总体目标会有所帮助。 我想我理解你想做什么,但你为什么要这样做会很高兴知道,因为可能有更好、更安全的方法来实现相同的结果。