简单示例$.post与servlet交互

index.jsp
---------------------------------------
<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Test</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function  onInvokeAction(){
$.post('url', {
    text: 'my string',
    number: 23
}, function(data) {
    $('#presidents').html(data);
});
}
</script>
</head>
<body onload="onInvokeAction()">
<input type="button"  value="12"  >
<div id="presidents"></div>
</body>
</html>

--------------------------------------------------------------
Ajax.java
-----------------------------------------------------


import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Ajax extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                response.setContentType("text/html");
                PrintWriter out = response.getWriter();
                out.println(String.valueOf(System.currentTimeMillis()));
                out.flush();
                out.close();
        }                       
}
-----------------------------------------------------------

至此我们就实现了简单的AJAX功能简单说一下代码,jsp页面的js代码很少,是调用了jQuery lib 实现
<script type="text/javascript">
function  onInvokeAction(){
$.post('url', {//request提交方式,如果是post 那么就是 $.post ,'/Ajax'是处理请求的servlet映射路径,也可以是struts里面的 .do,如果是GET方式提交那么就是$.get('url?parameter1=value&parameter2=value……')

text: 'my string',//需要设定的参数,servlet处理的时候request.getParameter("test")得到的就是“my string”

number: 23//同上,多个参数提交的格式为{name1:value,name2:value,name3:value}

}, function(data) {//定义AJAX回调函数,传入从servlet返回的“data”
 
  $('#presidents').html(data);//查找CSS样式ID为presidents的元素并以html格式 用“data”替换掉,data可以是html代码,例如“<input type='button' value ='hahaha'>”
});
}
</script>

===============================================

本文永久地址:https://sjolzy.cn/Interact-with-the-servlet-simple-example-post.html

--EOF--

标签: AJAX, servlet, jQuery

随机文章

已有 7 条评论

  1. batheobatheo

    sjolzy.cn is my top website, i love it !!
    free browser mmo

  2. 谢谢站长这样一个有意义的博客文章。给我留下了深刻的印象与你的看法 ????$.post?servlet?? - Jsp | Asp | .Net.

  3. giciloaUogiciloaUo

    thanks for this nice tips

  4. mrteslamrtesla

    DELETE THIS FUCKIN POST

    1. It just fuckin for you not for someone else /

  5. waiting for next post

添加新评论