在这第二天挣扎。我有一个带有标签列表的选择选项表单。我想根据所选标签显示数据库中的文章。我的 index.jsp 中有一个 div“showArticles”,我想在其中显示文章。我为此目的使用 jquery 和 ajax。我编写了名为 test 的 Servlet,我只输出了一个简单的字符串,但我什至无法接收到文本,似乎我的 servlet 从未被调用过。servlet 在名为“servlets”的包中,我使用的是 NetBeans。
这是表格:
<select id="b_sub_tag" name="b_sub_tag">
<option value='${0}'>Subject</option>
<c:forEach var="item" items="${subtagList}">
<option value='${item}'>${item}</option>
<c:set var="i" value='${i+1}'> </c:set>
</c:forEach>
</select>
这是jQuery:
$(document).ready(function(){
$("#b_sub_tag").change(function(){
var option_value = $(this).children('option:selected').val();
$.ajax({
type: "POST",
url: "test",
data :"value="+option_value,
success: function(html) {
$("#showArticles").html(html);
}
});
});
});
这是 Servlet:
@WebServlet(name = "test", urlPatterns = {"/test"})
public class test extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
/* TODO output your page here. You may use following sample code. */
//response.getWriter().write("Omething");
} finally {
out.close();
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
response.getWriter().write("Smething");
}
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
我试过 PrintWriter out = response.getWriter(); out.println("某事");
同样,什么也没有。我在 doPost() 中写入输出,我尝试在 doGet 和 processRequest 中写入,但没有运气。
任何人都知道为什么这不起作用?
问题已解决。我已将代码更改如下:
$.ajax({
url : "test",
type: 'GET',
***data: {value:option_value},***
error : function(jqXHR, textStatus, errorThrown) {
alert(textStatus);
},
success : function(html){
$("#showArticles").html(html);
}
}
});
小服务程序:
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
final InitialContext context = new InitialContext();
statefulb = (StatefulBeanRemote) context.lookup("java:comp/env/StatefulBeanRemote");
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write("A text");
} catch (NamingException ex) {
Logger.getLogger(LoadArticlesByTag.class.getName()).log(Level.SEVERE, null, ex);
}
}