How to save and edit a file using JavaScript?

后端 未结 5 1679
悲&欢浪女
悲&欢浪女 2020-12-06 02:44

I want a user of my website to enter some text in a text area and when he submits the form, the text that he entered be stored in a .txt file that is present in same directo

5条回答
  •  感动是毒
    2020-12-06 03:04

    You can send that particular textarea value through ajax by javascript. Then on the server side you can put a code, where you can accept the string and save it in a text file. You cant just do it with Javascript, you need a serverside code..

            //Html
        
    
        //javascript
        var dataVal = $('#TextArea').val();
        if(dataVal!="")
        {
        $.ajax({
                    url: '/createTextFile',
                    type: 'POST',
                    contentType: 'application/json; charset=utf-8',
                    data: dataVal,
                    success: function (response) {
                        alert('Success');      
                    },
                    error: function (xhr) {
                        alert('Error: There was some error while posting. Please try again later.');
                    }
                });
        }
    
        //You can server side code (C#)
    
        function SaveToTextFIle(text)
        {
            try
            {
                // The using statement automatically closes the stream and calls  
                // IDisposable.Dispose on the stream object. 
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt", true))
                {
                    file.WriteLine(text);
                }
            }
            catch(ex)
            {
                throw ex;
            }
        }
    

提交回复
热议问题