1

I m using jquery ajax to get the text file content and those need to show in the text area here is my front end code

function getFileText()
{
var fileName = "fileName.txt";
var data = {
        "fileName" : fileName
         }

$.ajax({
    "dataType": 'json',
    "type": "GET",
    "url": "getFileText.htm",
    "data":data ,
     cache:false,
    success :  function(resp){ 
        alert(resp);
    },
    error : function(XMLHttpRequest, textStatus, errorThrown){
        alert("error");
    }
});
}

<textarea id="fileTextArea" rows="35" cols="250">  </textarea>

HERE is My server side code

 public @ResponseBody String getFileText(HttpServletRequest request,HttpServletResponse response) throws IOException{
    String fileName = request.getParameter("fileName");
    String  dirname="D:/java/";
    FileInputStream file = new FileInputStream(new File(dirname+fileName));
    DataInputStream in = new DataInputStream(file);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;
    StringBuffer str = new StringBuffer();
    //Read File Line By Line
    while ((strLine = br.readLine()) != null)   {
      // Print the content on the console
        str.append(strLine);
        System.out.println(strLine);

    }

    //Close the input stream
    in.close();
    return str.toString();

}

My filename.txt something look like

<html>
<body>
    <b> Hi  user </b>,
    <br>
    <p>Welcome to FileText</p>
<body>
</html>

Now, I can able to get the response, but it is always going to the error block of ajax call and is showing parse Error,... "Unexpected token < "

Please help me . How to put the text file content into the response properly.

Krishnan
  • 185
  • 3
  • 11

4 Answers4

1

You should change dataType to text or html.

Datatype is you telling jQuery what kind of response to expect. So in your code you're expecting json.

$.ajax({
   "dataType": 'json',

Found a good explanation for datatype and contentType here ajax-datatype

Community
  • 1
  • 1
Tala
  • 8,888
  • 5
  • 34
  • 38
0

There is no closing tag for <br>. Use <br/>

Eduardo Sanchez-Ros
  • 1,777
  • 2
  • 18
  • 30
0

You also forgot to close <body> tag.

<html>
    <body>
        <b> Hi  user </b>,
        <br />
        <p>Welcome to FileText</p>
    </body>
</html>
Flaëndil
  • 118
  • 6
-1

I changed the

$.ajax({
"dataType": 'json',

to $.ajax({ "dataType": 'text',

now it is working..

Thanks..

Krishnan
  • 185
  • 3
  • 11