我写了一些代码来保存和下载textarea中的文本作为文件,我使用Ajax将textarea值传递给服务器端PHP代码。这是我的Ajax代码:
function saveFile()
{
document.getElementById("save").childNodes[0].nodeValue="Saving";
var values = {
"txTitle": document.getElementById("title").value,
"tex": document.getElementById("textar").value
};
$.ajax({
url: "SaveFile.php",
type: "POST",
data: values,
cache: false,
success: function(data){
document.getElementById("save").childNodes[0].nodeValue="Save";
}
});
return false;
}
这里是SaveFile.php文件中的代码:
<?php
$tex = $_POST['tex'];
$txTitle = str_replace(array('\'', '"'), '', trim($_POST['txTitle']));
header('Content-Description: File Transfer');
header('Connection: Keep-Alive');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-type: text/plain');
header('Content-Disposition: attachment; filename='.str_replace(' ','-',$txTitle));
header('Content-Length: ' . mb_strlen($tex, '8bit'));
echo $tex;
?>