我希望这个简洁的解释能给你一个概述和你期望的理解。
第一部分
服务器端
在您服务器上的 Web 服务器应用程序中,如果使用 Java,您将创建一个 Java servlet 类来处理从客户端浏览器通过脚本或表单提交的数据,并提供动态内容,例如来自客户端的数据库查询结果.
阅读更多关于 Servlet 的信息:
- http://docs.oracle.com/javaee/5/tutorial/doc/bnafe.html
- http://en.wikipedia.org/wiki/Java_Servlet
- 什么是 Java Servlet?
另请阅读有关如何在服务器上注册 servlet 的更多信息(java 项目的 web.xml)
servlet 示例:
-=================-
@WebServlet(name = "MyServlet", urlPatterns = {"/calculator"}, asyncSupported = true)
public class MyServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Enumeration e = request.getParameterNames(); // parsing the string from client
while (e.hasMoreElements()) {
String name = (String) e.nextElement();// eg. "command" from ajax
String value = request.getParameter(name); // eg. getSum
if (value.equals("getSum")) {
// Instantiate a java class and call the method
// that performs the addition and returns the value
Calculator calc = new Calculator();
String answer = (String) calc.getSum();
if (answer != null) {
// Set contentType of response to client or browser
// so that jQuery knows what to expect.
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
// return answer to ajax calling method in browser
out.print(answer);
out.close();
}
}
} // END While LOOP
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// include method if you call POST in you ajax on client side
}
}
用于计算服务器路径的 Java 类
public class Calculator {
public int getSum() {
return 10+15;
}
}
-
B部分
客户端——您的浏览器
-=======================-
您必须访问 jQuery 网站,下载并添加 jQuery ajax 脚本到您的项目中。“jquery-ui.min.js”足以满足此目的。使用以下行将此脚本添加到您的 html 或 jsp 文件中:
<script src="resources/ajax/libs/jqueryui/1.8/jquery-ui.min.js" type="text/javascript"></script>
在您的外部 javascript 文件或内联 javascript 中包含一个调用 servlet 并获取总和的函数,如下所示:
function getSum(){
$.ajax({
type: 'GET', // type of request to make. method doGet of the Servlet will execute
dataType: 'text', // specifying the type of data you're expecting back from the server
url: 'calculator', // the URL to send the request to. see annotation before class declaration
data: "command="+"getSum", // Data to be sent to the server (query string)
// if request fails this method executes
error:
function(e){
alert('Error. Unable to get response from server');
},
// when request is successful, this function executes
// display the data from server in an alert
success:
function(result){
if(result) {
alert(result);
}
}
});
}