首页 > 代码库 > ajax交互方法实现

ajax交互方法实现

AJAX = 异步 JavaScript 和 XML。

AJAX 是一种用于创建快速动态网页的技术。

通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。

传统的网页(不使用 AJAX)如果需要更新内容,必需重载整个网页面。

可使用jQuery的Ajax与Java通过POST方式进行交互

实现代码样例具体如下:

html代码

 

<body>
    <div id="main">
        <button id="myBut">Ajax获取数据</button>
        <div id="container"></div>
    </div>
</body>

 

style代码

<style type="text/css">
#main {
    margin: 0 auto;
    width: 400px;
}
#container {
    width: 400px;
    height: 300px;
    border: 1px dashed #666;
    text-align: center;
    line-height: 300px;
}
</style>

javastript代码

<script type="text/javascript" src="http://www.mamicode.com/js/jquery-1.8.3.js"></script>
<script type="text/javascript">
    $(function() {
        $(‘#myBut‘).click(function() {
            $.post("JqueryAjaxServlet", {
                age : 18,
                name : "zhang"
            }, function(data, textStatus) {
                var container = $(‘#container‘);
                var resultData =http://www.mamicode.com/ $.parseJSON(data);
                var age = resultData.age;
                var name = resultData.name;
                container.html("name:" + name + "," + "age:" + age);
            });
        });
    });
</script>

java代码

public class JqueryAjaxServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String age = request.getParameter("age");
        String name = request.getParameter("name");

        String personJSON = "{\"name" + "\":\"" + name + "\"," + "\"age"
                + "\":" + age + "}";
        System.out.println(personJSON);
        response.getWriter().write(personJSON);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        doGet(request, response);

    }

}

web.xml代码

<servlet>
    <servlet-name>JqueryAjaxServlet</servlet-name>
    <servlet-class>com.jquery.ajax.com.JqueryAjaxServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>JqueryAjaxServlet</servlet-name>
    <url-pattern>/JqueryAjaxServlet</url-pattern>
  </servlet-mapping>    
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

另附其他实现代码:

ajax调用后台java类的例子  blog.csdn.net/rznice/article/details/43561645

 java + jquery + ajax + json 交互 http://yangchunhe.iteye.com/blog/1751239

 

ajax交互方法实现