我正在使用 jquery ajax 来获取文本文件内容,那些需要在文本区域显示的内容是我的前端代码
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>
这是我的服务器端代码
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();
}
我的 filename.txt 看起来像
<html>
<body>
<b> Hi user </b>,
<br>
<p>Welcome to FileText</p>
<body>
</html>
现在,我可以得到响应,但它总是会转到 ajax 调用的错误块并显示 parse Error,...“Unexpected token <”
请帮我 。如何正确地将文本文件内容放入响应中。