简体   繁体   English

使用PHP将Javascript字符串保存到.TXT文件

[英]Save Javascript string to .TXT file with PHP

Sorry if this is a little rambling and takes in a few subjects. 抱歉,这有点杂乱无章,并涉及了一些主题。 I will try to keep it straightforward and say off the bat that I am new to JS, jQuery and PHP :) 我会尽量保持直截了当,并说出我是JS,jQuery和PHP的新手:)

I have some JS that generates a string and I want to save this string in a plain text (.txt) file to the users local machine. 我有一些生成字符串的JS,我想将此字符串以纯文本(.txt)文件格式保存到用户本地计算机。

I have a PHP file set up that simply does this: 我设置了一个PHP文件,它可以简单地做到这一点:

header('Content-type: text/plain');
header('Content-Disposition: attachment; filename="testFile.txt"');
echo "Saved Data";

If I navigate straight to this page then I get testFile.txt appear in my Downloads folder. 如果我直接导​​航到此页面,则会在我的下载文件夹中看到testFile.txt。 All good so far so I tried to send my string from the JS using: 到目前为止一切都很好,所以我尝试使用以下命令从JS发送我的字符串:

$.post("_php/writeFile.php",
{
    data:"Test Data"
},
function(data, status)
{
    alert("Data: " + data + "\nStatus: " + status);
});

Now when I run this the alert fires and reads the 'Saved Data' string so I assume the PHP is getting reached but the download does not trigger. 现在,当我运行此命令时,警报将触发并读取“已保存的数据”字符串,因此我认为已到达PHP,但不会触发下载。

If anyone can explain whats going on here for my own education that would be great. 如果有人能解释我自己的教育现状,那将很棒。 If you can suggest how to get it working then that would be even better for my sanity :) 如果您可以提出如何使其工作的建议,那对于我的理智会更好:)

Cheers all. 欢呼

Downloading a file can't be triggered by an ajax request. ajax请求无法触发下载文件。 You will have to either use a GET request instead, navigating to the actual url, like window.location.href = '_php/writeFile.php' , or submit a form with the same URL as its action. 您将不得不使用GET请求来代替,导航至实际的URL,例如window.location.href = '_php/writeFile.php' ,或提交具有与其操作相同的URL的表单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM