zoukankan      html  css  js  c++  java
  • Ajax案例1-->GET请求

    jsp页面--firstajax.jsp


    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <script type="text/javascript">
    
    //使用function获取XMLHttpRequest对象
    function createXMLHttpRequest(){
        try{
            return new XMLHttpRequest();//一般的大众的浏览器
        }catch(e){
            try{
                return new ActiveXObject("Msxml2.XMLHTTP");//IE6
            }catch(e){
                try{
                    return new ActiveXObject("Microsoft.XMLHTTP");    //IE5.5及以下
                }catch(e){
                    alert("你的浏览器是远古时代的吗?");
                }
            }
        }
    };
    
    window.onload= function(){
        
        var btn = document.getElementById("btn");
        btn.onclick = function(){
           //1.得到对象
            var xmlHttp = createXMLHttpRequest();
            //2.打开连接
            xmlHttp.open("GET","<c:url value='/FirstServlet'/>",true);
            //3.发送请求
            xmlHttp.send(null);
            //4.接收服务器响应
            xmlHttp.onreadystatechange = function(){
                if(xmlHttp.readyState ==4 && xmlHttp.status == 200){
                    var text =xmlHttp.responseText;
                    //完成逻辑
                    var h1 = document.getElementById("h1");//获得h1标签
                    
                    h1.innerHTML = text ;//把服务器响应的信息写到h1标签中
                }
            };
        };        
    };
    
    </script>
    <%--
    1.给一个按钮,以及一个标题
    2.点击按钮时向服务器发送一步请求,得到结果
    3.把响应结果显示到标题中
    --%>
    
    <body>
    <button id = "btn">获得服务器端servlet的数据</button>
    <h1 id="h1"></h1>
    </body>
    </html>

    Servlet-->FirstServlet.java


    package ajax;
    
    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class FirstServlet extends HttpServlet {
    
        private static final long serialVersionUID = -1866369869941762275L;
    
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            
             response.getWriter().print("Hello Ajax!!!");
        }
    }

    图片展示:


  • 相关阅读:
    Python中匿名函数的应用
    Python中界面阻塞情况的解决方案
    Python中的协程,gevent模块
    Python中的进程和线程
    Python中的正则表达式用法
    Jquery瀑布流效果(下篇)
    安卓不支持keypress事件
    让MAC OS也能使用LL LA L等LS的别名
    git 常用命令
    javascript中的apply与call
  • 原文地址:https://www.cnblogs.com/vmkash/p/5521316.html
Copyright © 2011-2022 走看看