這是我的JSP頁面來POST請求無法使用jQuery
<%@頁面語言= 「Java」 的的contentType = 「text/html的;字符集= UTF-8」 的pageEncoding = 「UTF-8」 %>
<script type="text/javascript" src="/js/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
var jq = jQuery.noConflict();
function add()
{
alert("inside add");
jq(function() {
alert("inside jq function");
jq.post("/ajax.htm",
{ inputNumber1: jq("#inputNumber1").val(),
inputNumber2: jq("#inputNumber2").val() },
function(data){
// data contains the result
// Assign result to the sum id
jq("#sum").replaceWith('<span id="sum">'+ data + '</span>');
});
});
}
</script>
<title>Spring MVC - jQuery Integration Tutorial</title>
</head>
<body>
<h3>Spring MVC - jQuery Integration Tutorial</h3>
<h4>AJAX version</h4>
Demo 1
<div style="border: 1px solid #ccc; width: 250px;">
Add Two Numbers: <br/>
<input id="inputNumber1" type="text" size="5"> +
<input id="inputNumber2" type="text" size="5">
<input type="submit" value="Add" onclick="add()" /> <br/>
Sum: <span id="sum">(Result will be shown here)</span>
</div>
</body>
</html>
這是在彈簧控制器
package com.vaannila.web;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/ajax.htm")
public class AjaxController {
@RequestMapping(method = RequestMethod.GET)
public String getAjaxAddPage() {
System.out.println("inside get ajax add page");
return "ajax";
}
@RequestMapping(method = RequestMethod.POST)
public @ResponseBody Integer add(@RequestParam(value="inputNumber1", required=true) Integer inputNumber1,
@RequestParam(value="inputNumber2", required=true) Integer inputNumber2,
Model model) {
System.out.println("inside post method");
Integer sum=inputNumber1+inputNumber2;
return sum;
}
}
該頁面正在顯示,但輸入兩個數字後,當我按下添加時,功能添加沒有被調用。
螢火蟲和tomcat控制檯說什麼? – Bozho 2011-04-20 11:03:43
我只收到一個警告「內部添加」,之後沒有任何顯示 – elle 2011-04-20 11:06:02
@elle - 是的,但是響應狀態是什麼? Firebug應該說。另外,如果出現問題,spring會在服務器日誌中記錄一條消息 – Bozho 2011-04-20 11:08:40