将 JS 变量数据发送到可下载页面
Sending JS variable data to a downloadable page
这个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可访问的文件,其中包含他们在服务器上想要的任何内容。 如前所述,澄清您的总体目标会有所帮助。 我想我理解你想做什么,但你为什么要这样做会很高兴知道,因为可能有更好、更安全的方法来实现相同的结果。
相关文章:
- 通过php页面中的js强制下载txt
- 如何在node.js中只下载文件的前10 KB
- 使用angular js在前端下载文件
- 在fabric.js中以PNG格式下载Canvas,给出网络错误
- 如何使用nginx强制下载js文件
- 无法使用Angular JS和spring MVC打开下载文件
- 无法使用API-node.js从Google Drive下载文件
- 如何使用 Node.js 下载文件(不使用第三方库)
- 使用音频.js单击按钮下载音频
- 巴比伦JS-场景从本地文件下载
- 在Asp.net的空网站中,如何改变"Web.config”;使内容(.js)文件显示在浏览器中,而不是下载
- node.js+cheerio-scrape:传递一个要下载的url数组
- Chocolat.JS-将标题转换为下载按钮-将span类内容移动到href中
- 创建文件下载js
- https 域,请尝试从不安全的 http 下载 JS
- 下载js GET请求返回的带有唯一密钥的文件
- 我们可以下载.js文件和图像P2P
- 延迟下载.js文件到最后
- 从url下载js脚本代码
- 如何下载JS附加值作为HTML文件