[英]returning JSP value to AJAX call
我已經對JSP進行了AJAX調用,而JSP又在單獨的Java類中調用了Java方法。 所有文件都在同一文件夾中。
由於某些原因,我無法將正確的值返回給AJAX。 它只是打印整個JSP內容。
JavaScript的:
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if(true){
alert('hello!');
var response = xhr.responseText;
alert(response);
document.getElementById('newgame').innerHTML = xhr.responseText;
}
};
xhr.open('GET', 'javaconnect.jsp', true);
xhr.send(null);
JSP:
<%@ page import="com.example.Server"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
Server tc = new Server();
out.print(tc.highScore());
%>
</body>
</html>
Java類:
package com.example;
public class Server {
public String highScore() {
return "hello!!!";
}
}
最好的解決方案是使用Servlet代替實例化Server類的jsp來構成控制層,例如:
public class HelloWorld extends HttpServlet {
protected void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
Server tc = new Server();
String txt = tc.highScore();
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(txt);
}
}
不要忘記映射servlet並更改ajax調用的url。 您可以測試通話
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.