我編寫了一個Web應用程序,並嘗試瞭解Ajax如何工作。 當我嘗試選擇一個類別並且沒有發生錯誤時沒有任何反應。調用JavaScript函數時JSP上沒有任何反應
JSP頁面:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<link media="all" rel="stylesheet" type="text/css" href="resources/css/all.css" />
<script type="text/javascript" src="resources/js/jquery-1.7.2.min.js"/>
<script type="text/javascript">
var categoryName;
$(document).ready(function() {
function doAjaxPost(){
categoryName = $('#selectCategory').val();
$.ajax({
type : "Get",
url : "loadProducts",
data : "Category selected =" + categoryName,
success : function(response) {
alert(response);
},
error : function(e) {
alert('Error: ' + e);
}
});
}
});
$("#selectCategory").on("change", doAjaxPost());
</script>
<title>Waiter</title>
</head>
<body>
<h3>Waiter's page </h3>
<h2>
Welcome : ${pageContext.request.userPrincipal.name}
<a href="/logout" class="btn-on">Logout</a>
</h2>
<br>
<c:if test="${!empty productCategoriesList}">
<spring:message code="label.category" />
<select id="selectCategory" name="productCategory">
<option value=" "></option>
<c:forEach items="${productCategoriesList}" var="productCategory">
<option value=${productCategory.id}>${productCategory.productType}</option>
</c:forEach>
</select>
</c:if>
<div id = "product">
<spring:message code="label.product" />
<select>
<option value = ""></option>
</select>
</div>
我的春天控制器:
@RequestMapping(value = "/loadProducts")
public @ResponseBody String loadProducts(@RequestParam("categoryName")
String categoryName){
System.out.println(categoryName);
String str = "Category selected: " + categoryName;
return str;
}
應該怎樣才能使此功能工作?
嘗試移動你的'在( '變')'函數在你的'$(document).ready()'函數裏面 – Lixus
@Lixus試過了,但得到了同樣的錯誤。如果我從我的選擇標記中刪除「onchange = doAjaxPost()」 - 錯誤未顯示,但也沒有任何反應。 – Volcano91
更新您的問題,以便我們可以看到您所做的事情。 –