首页 > 社区问答列表 >将TypeScript/Angular客户端生成的服务器端文本文件中的问题

  将TypeScript/Angular客户端生成的服务器端文本文件中的问题

"问题在于,我正试图通过Client浏览器发起的请求将文本内容写入服务器端文件。NOTE:这已经是相当长的时间以来,我对TypeScript/PHP/服务器的工作了,所以请不要假设我默认就知道一切:)我根据自己的代码进行了修改:/问题/11240996/将JavaScript输出到文件中-server

我最终得到了一个使用PHP服务器端创建文件"h.txt"的代码。确实是创建了一个空文件"h.txt",但它的内容"456"从未写入:我从未收到关于原因的错误消息。"456"是文件的内容,


服务器端

//PHP code:  (A little elaborate, but it should work)

//h.txt is created, but its content is never written: read only problem?? I can't find how to see if //the file is read only or not)

//The php Code is located on Server

//On the Client side I have the following code:
//The Client is written in Angular, and the function that triggers the data exchange with server

testWriteToServerFile() {

        let data: string = "456";// this is your data that you want to pass to the server 
        //next you would initiate a XMLHTTPRequest as following (could be more advanced):

        var url = url to the server side PHP code that will receive the data.

        var http = new XMLHttpRequest();
        http.open("POST", url, true);

        //Send the proper header information along with the request
        http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        http.setRequestHeader("Content-length", data.length.toString());
        http.setRequestHeader("Connection", "close");

         http.onreadystatechange = function() {//Call a function when the state changes.
            if(http.readyState == 4 && http.status == 200) {
                alert(http.responseText);//check if the data was received successfully.
            }
        }
        http.send(data);
}

(我试图包括适当的链接到服务器等,但这篇文章被归类为垃圾邮件?)

服务器上的h.txt对客户端是只读的问题吗?解决方案是什么?

我希望能够将文本写入服务器上的h.txt文件。


P粉022140576
P粉022140576

  • P粉135799949
  • P粉135799949   采纳为最佳   2023-08-08 13:53:33 1楼

    好的,在这里您以写入方式打开一个文本文件,然后立即关闭它。

    function getData() {
      $myFile = fopen("h.txt", "w");
      fclose($myFile);
      sleep(5);

    您实际上需要做的是将内容写入数据变量中,然后以像这样的方式将网址作为参数传入:

    function getData() {
    $myFile = fopen("h.txt", "w");
    fwrite($myFile, filter_input(INPUT_POST, 'data', FILTER_SANITIZE_SPECIAL_CHARS));
    fclose($myFile);

    我也个人更喜欢输入内容(input_put_content())而不是fopen/fclose。

    +0 添加回复