1
我想調用這個servlet使用Ajax jQuery中:
@WebServlet("/getCoursesForSubject")
public class GetCoursesForSubjectServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public GetCoursesForSubjectServlet() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
...........
而在JSP頁面中我有這樣的jQuery代碼調用Ajax請求:
$("#subjectSelect").change(function(){
var name = $("#subjectSelect option:selected").text();
alert("change handler is called "+name);
$.get("/getCoursesForSubject",{"subjectName":name},function(responseJson){
$.each(responseJson,function(index,course){
alert(course);
$("<option>").appendTo($("#courseSelect")).text(course.courseDescriptionName);
});
});
});
的change
方法被調用,警報dsplayed正確:
alert("change handler is called "+name);
不過下次我希望被調用的路徑/getCoursesForSubject
的Java Servlet,但事實並非如此。
谷歌瀏覽器的控制檯,我得到這個錯誤:
GET http://localhost:8080/getCoursesForSubject?subjectName=AS%20-%20Aerospace%20Studies%22 404()
這意味着Ajax調用製成,但服務器返回404錯誤。
這是解決通過給contextPath
URL。正確$.get
方法是:
$.get("${pageContext.request.contextPath}/getCoursesForSubject",{"subjectName":name},function(responseJson){
$.each(responseJson,function(index,course){
alert(course);
$("<option>").appendTo($("#courseSelect")).text(course.courseDescriptionName);
});
});
你能直接在瀏覽器地址欄中訪問這個URL嗎? – Nitesh
我相信你正在發送一個帖子請求(因爲你發佈數據)不是? – Sletheren