我尝试使用从访问Glassfish服务器上的EJB的servlet检索的数据创建图形。在实现图之前,我正在测试servlet,所以我使用javascript ajax调用来检索数据,将servlet的结果(一个JSON格式的字符串)写入div(id ="子标题&#34 ;)
结果是屏幕上没有任何内容。 此外,使用浏览器中的工具检查ajax调用的结果,似乎返回一个空字符串,并且url似乎是正确的。实际上我在javascript行中放了一个断点,包括调用jquery.html(...)函数,数据变量的内容显示为空。
奇怪的是,如果我将完整的URL放在浏览器上,则会正确返回JSON字符串。
它不应该是一个跨脚本问题,因为我无法访问外部服务器。任何提示?
servlet:
/**
* Servlet implementation class RetrieveHistory
*/
@WebServlet("/history")
public class RetrieveHistory extends HttpServlet {
private static final long serialVersionUID = 1L;
List<Measure> measures;
@EJB
MeasureEJB measureEjb;
/**
* @see HttpServlet#HttpServlet()
*/
public RetrieveHistory() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
measures = measureEjb.findMeasures();
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(new Gson().toJson(measures));
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
javascript
<script>
$.ajax({
url: 'history',
success: function(data) {
$('#sub-title').html(data);
}
});
</script>
被调用的servlet的URL
http://localhost:8080/Smarthome-0.0.1-SNAPSHOT/history
调用servlet的url
http://localhost:8080/Smarthome-0.0.1-SNAPSHOT/dashboard