zoukankan      html  css  js  c++  java
  • 最简单的ajax示例

     

    首先我们创建一个some.jsp如下(注意:不要将JSP文件放在子文件夹中,如果你这样做,请相应地更改servlet URL):

    <!DOCTYPE html>

    <html lang="en">

        <head>

            <title>TestAjax</title>

            <script src="http://code.jquery.com/jquery-latest.min.js"></script>

            <script>

                $(document).on("click", "#somebutton", function() {

                    $.get("someservlet", function(responseText) {   

                        $("#somediv").text(responseText);         

                    });

                });

            </script>

        </head>

        <body>

            <button id="somebutton">press here</button>

            <div id="somediv"></div>

        </body>

    </html>

    使用如下doGet()方法创建一个servlet 

    @Override

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String text = "some text";

        response.setContentType("text/plain");  // Set content type of the response so that jQuery knows what it can expect.

        response.setCharacterEncoding("UTF-8"); // You want world domination, huh?

        response.getWriter().write(text);       // Write response body.

    }

    将该servlet映射到URL模式/someservlet/someservlet/*下面(URL模式可以自由选择,但需要将someservlet所有位置相应地更改JS代码示例中的URL):

    @WebServlet("/someservlet/*")

    public class SomeServlet extends HttpServlet {

        // ...

    }

    或者,当尚未使用Servlet 3.0兼容容器(Tomcat 7Glassfish 3JBoss AS 6等或更新版本)时,请以web.xml旧式进行映射:

    <servlet>

        <servlet-name>someservlet</servlet-name>

        <servlet-class>com.example.SomeServlet</servlet-class>

    </servlet>

    <servlet-mapping>

        <servlet-name>someservlet</servlet-name>

        <url-pattern>/someservlet/*</url-pattern>

    </servlet-mapping>

    现在在浏览器中打开http// localhost8080 / context / some.jsp,然后按按钮。将看到,使用servlet响应更新了的div内容。

  • 相关阅读:
    github入门到上传本地项目
    17-索引
    16-pymysql模块的使用
    15-可视化工具Navicat的使用
    C语言/C++知识
    Apk反编译那些事
    CTF基本常识
    WebView net::ERR_CLEARTEXT_NOT_PERMITTED&&net::ERR_INTERNET_DISCONNECTED
    测试
    zookeeper-3.4.5安装&3台机器安装之后 ./zkServer.sh status 之后会显示“Error contacting service. It is probably not running.”的解决办法
  • 原文地址:https://www.cnblogs.com/woniuxy/p/7428779.html
Copyright © 2011-2022 走看看