保存使用JavaScript在服务器上的文本文件 [英] Saving a text file on server using JavaScript
问题描述
是否有可能保存文本使用JavaScript / jQuery的不使用PHP的一个新的文本文件?我试图挽救可能包含HTML实体,JS,HTML,CSS和PHP脚本,我不想逃避,或使用urlen code文本!
Is it possible to save text to a new text file using JavaScript/jQuery without using PHP? The text I'm trying to save may contain HTML entities, JS, HTML, CSS and PHP scripts that I don't want to escape or use urlencode!
如果它只是可以使用PHP来实现我怎么能不通过编码到PHP中的文字?
If it's only can be achieved using PHP how can I pass the text to PHP without encoding it?
推荐答案
您必须有一个服务器端脚本来处理你的请求时,它不能使用JavaScript实现。
You must have a server-side script to handle your request, it can't be done using javascript.
要发送的原始数据,而无需的URIEncoding或转义特殊字符到PHP,并将其保存为新的 TXT
文件,您可以使用后发送Ajax请求
方法和 FORMDATA
这样的:
To send raw data without URIencoding or escaping special characters to the php and save it as new txt
file you can send ajax request using post
method and FormData
like:
记者:
var data = new FormData();
data.append("data" , "the_text_you_want_to_save");
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new activeXObject("Microsoft.XMLHTTP");
xhr.open( 'post', '/path/to/php', true );
xhr.send(data);
PHP:
if(!empty($_POST['data'])){
$data = $_POST['data'];
$fname = mktime() . ".txt";//generates random name
$file = fopen("upload/" .$fname, 'w');//creates new file
fwrite($file, $data);
fclose($file);
}
编辑:
由于弗洛里安下面所提到的,是不是因为 FORMDATA
所需的XHR回退,不支持旧版浏览器(的 FORMDATA浏览器compatibiltiy ),所以你可以声明XHR变量:
As Florian mentioned below, the XHR fallback is not required since FormData
is not supported in older browsers (formdata browser compatibiltiy), so you can declare XHR variable as:
var xhr = new XMLHttpRequest();
另外,请注意,这仅适用于支持 FORMDATA
如IE +10。
这篇关于保存使用JavaScript在服务器上的文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!