zoukankan      html  css  js  c++  java
  • ajax 三种数据格式

    1.JSON(格式要正确,可以引jar包操作)

    servlet代码

     1 package com.hsp.action;
     2 
     3 import java.io.IOException;
     4 import java.io.PrintWriter;
     5 
     6 import javax.json.JsonString;
     7 import javax.servlet.ServletException;
     8 import javax.servlet.annotation.WebServlet;
     9 import javax.servlet.http.HttpServlet;
    10 import javax.servlet.http.HttpServletRequest;
    11 import javax.servlet.http.HttpServletResponse;
    12 
    13 /**
    14  * Servlet implementation class showCities
    15  */
    16 @WebServlet("/showCities")
    17 public class showCities extends HttpServlet {
    18     private static final long serialVersionUID = 1L;
    19        
    20     /**
    21      * @see HttpServlet#HttpServlet()
    22      */
    23     public showCities() {
    24         super();
    25         // TODO Auto-generated constructor stub
    26     }
    27 
    28     /**
    29      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
    30      */
    31     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    32         // TODO Auto-generated method stub
    33     }
    34 
    35     /**
    36      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
    37      */
    38     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    39         // TODO Auto-generated method stub
    40         response.setContentType("text/xml;charset=utf-8");  
    41         response.setHeader("Cache-Control", "no-cache");
    42         
    43         //接收用户选择的省的名字
    44         String shengString=request.getParameter("province");
    45         System.out.println(shengString);
    46         PrintWriter out=response.getWriter();
    47         StringBuilder builder=new StringBuilder();
    48       
    49 
    50         String info="";
    51 
    52 //        if ("zhejiang".equals(shengString)) {
    53 //            System.out.println("浙江");
    54 //            info="<province><city>杭州</city><city>温州</city><city>宁波</city></province>";
    55 //        }
    56 //        else if ("jiangsu".equals(shengString)) {
    57 //            System.out.println("江苏");
    58 //
    59 //            info="<province><city>南京</city><city>徐州</city><city>苏州</city></province>";
    60 //        }
    61         if ("zhejiang".equals(shengString))
    62         {
    63             info= "[{"+'"'+"city"+'"'+":"+'"'+"杭州"+'"'+"},{"+'"'+"city"+'"'+":"+'"'+"温州"+'"'+"}]";
    64         }
    65         else if ("jiangsu".equals(shengString)) {
    66             info= "[{"+'"'+"city"+'"'+":"+'"'+"南京"+'"'+"},{"+'"'+"city"+'"'+":"+'"'+"苏州"+'"'+"}]";
    67 
    68         }
    69         System.out.println("{"+'"'+"ins"+'"'+":"+info+"}");
    70        builder.append("{"+'"'+"ins"+'"'+":"+info+"}");
    71 
    72        out.println(builder.toString());
    73     }
    74 
    75 }

    jsp代码

      1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
      2 <%
      3 String path = request.getContextPath();
      4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
      5 %>
      6 
      7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
      8 <html>
      9   <head>
     10     <base href="<%=basePath%>">
     11     
     12     <title>My JSP 'Mycity.jsp' starting page</title>
     13     
     14     <meta http-equiv="pragma" content="no-cache">
     15     <meta http-equiv="cache-control" content="no-cache">
     16     <meta http-equiv="expires" content="0">    
     17     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
     18     <meta http-equiv="description" content="This is my page">
     19     <!--
     20     <link rel="stylesheet" type="text/css" href="styles.css">
     21     -->
     22 
     23   </head>
     24   
     25   <body>
     26   <script type="text/javascript">
     27    //1.创建ajax引擎
     28   function getXmlHttpObject(){
     29   var xmlHttpRequest;
     30   //不同的浏览器获取对象xmlhttprequest对象方法不一样
     31   if(window.ActiveXobject)
     32   {
     33       xmlHttpRequest=new ActiveXobject("Microsoft.XMLHTTP");
     34   }
     35   else
     36   {
     37         xmlHttpRequest=new XMLHttpRequest();
     38   }
     39   return xmlHttpRequest;
     40   }
     41  
     42  //新建myXmlHttpRequest对象
     43  var myXmlHttpRequest="";
     44   
     45   function getCities(){
     46   //创建对象
     47       myXmlHttpRequest=getXmlHttpObject();
     48        // window.alert(myXmlHttpRequest);
     49       //如果创建成功,则进行post请求
     50       if(myXmlHttpRequest){
     51       //创建url
     52       var url="/ajax/showCities";//post
     53       //携带的参数
     54       var data="province="+$('sheng').value;
     55       //
     56       myXmlHttpRequest.open("post",url,true);
     57       //必填
     58       myXmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
     59       //指定回调函数
     60             myXmlHttpRequest.onreadystatechange=chuli;
     61       //发送请求
     62       myXmlHttpRequest.send(data);
     63       
     64       }
     65       
     66       
     67   }
     68   
     69   function chuli(){
     70       if(myXmlHttpRequest.readyState==4){
     71             var mes=    myXmlHttpRequest.responseText;
     72       window.alert(mes);
     73       var mes_obj=eval("("+mes+")");
     74       window.alert(mes_obj);
     75       window.alert(mes_obj.ins[0].city);
     76       // $('myres').value=mes_obj.info;
     77       
     78       
     79       //取出xml格式数据
     80           /* if(myXmlHttpRequest.status==200)
     81           {          
     82               //取出服务器回送的数据
     83               window.alert(myXmlHttpRequest.responseXML);
     84               var cities= (myXmlHttpRequest.responseXML.getElementsByTagName("city"));
     85               //window.alert(cities.length);
     86               //alert(cities[1].lastChild.nodeValue);
     87               for(var i=0;i<cities.length;i++)
     88               {alert(cities[i].childNodes[0].nodeValue);}
     89           } */
     90       
     91       }
     92       
     93   }
     94   
     95   
     96    function $(id)
     97   {
     98   return document.getElementById(id);
     99   }
    100   
    101   </script>
    102   
    103   
    104     This is my JSP page. <br>
    105     
    106     <select id="sheng" onchange="getCities();">
    107     <option value="">---省---</option>
    108     <option value="zhejiang">浙江</option>
    109     <option value="jiangsu">江苏</option>
    110     </select>
    111     
    112     <select id="city" onchange="sendRequest();">
    113     <option value="">--城市--</option>
    114     </select>
    115     
    116      <select id="country" onchange="sendRequest();">
    117     <option value="">--县城--</option>
    118     </select>
    119     
    120   </body>
    121 </html>

    2.xml格式

    servlet代码

     1 package com.hsp.action;
     2 
     3 import java.io.IOException;
     4 import java.io.PrintWriter;
     5 
     6 import javax.json.JsonString;
     7 import javax.servlet.ServletException;
     8 import javax.servlet.annotation.WebServlet;
     9 import javax.servlet.http.HttpServlet;
    10 import javax.servlet.http.HttpServletRequest;
    11 import javax.servlet.http.HttpServletResponse;
    12 
    13 /**
    14  * Servlet implementation class showCities
    15  */
    16 @WebServlet("/showCities")
    17 public class showCities extends HttpServlet {
    18     private static final long serialVersionUID = 1L;
    19        
    20     /**
    21      * @see HttpServlet#HttpServlet()
    22      */
    23     public showCities() {
    24         super();
    25         // TODO Auto-generated constructor stub
    26     }
    27 
    28     /**
    29      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
    30      */
    31     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    32         // TODO Auto-generated method stub
    33     }
    34 
    35     /**
    36      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
    37      */
    38     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    39         // TODO Auto-generated method stub
    40         response.setContentType("text/xml;charset=utf-8");  
    41         response.setHeader("Cache-Control", "no-cache");
    42         
    43         //接收用户选择的省的名字
    44         String shengString=request.getParameter("province");
    45         System.out.println(shengString);
    46         PrintWriter out=response.getWriter();
    47         StringBuilder builder=new StringBuilder();
    48       
    49 
    50         String info="";
    51 
    52         if ("zhejiang".equals(shengString)) {
    53             System.out.println("浙江");
    54             info="<province><city>杭州</city><city>温州</city><city>宁波</city></province>";
    55         }
    56         else if ("jiangsu".equals(shengString)) {
    57             System.out.println("江苏");
    58 
    59             info="<province><city>南京</city><city>徐州</city><city>苏州</city></province>";
    60         }
    61 //        if ("zhejiang".equals(shengString))
    62 //        {
    63 //            info= "[{"+'"'+"city"+'"'+":"+'"'+"杭州"+'"'+"},{"+'"'+"city"+'"'+":"+'"'+"温州"+'"'+"}]";
    64 //        }
    65 //        else if ("jiangsu".equals(shengString)) {
    66 //            info= "[{"+'"'+"city"+'"'+":"+'"'+"南京"+'"'+"},{"+'"'+"city"+'"'+":"+'"'+"苏州"+'"'+"}]";
    67 //
    68 //        }
    69 //        System.out.println("{"+'"'+"ins"+'"'+":"+info+"}");
    70 //       builder.append("{"+'"'+"ins"+'"'+":"+info+"}");
    71         builder.append(info);
    72        out.println(builder.toString());
    73     }
    74 
    75 }

    jsp代码

      1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
      2 <%
      3 String path = request.getContextPath();
      4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
      5 %>
      6 
      7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
      8 <html>
      9   <head>
     10     <base href="<%=basePath%>">
     11     
     12     <title>My JSP 'Mycity.jsp' starting page</title>
     13     
     14     <meta http-equiv="pragma" content="no-cache">
     15     <meta http-equiv="cache-control" content="no-cache">
     16     <meta http-equiv="expires" content="0">    
     17     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
     18     <meta http-equiv="description" content="This is my page">
     19     <!--
     20     <link rel="stylesheet" type="text/css" href="styles.css">
     21     -->
     22 
     23   </head>
     24   
     25   <body>
     26   <script type="text/javascript">
     27    //1.创建ajax引擎
     28   function getXmlHttpObject(){
     29   var xmlHttpRequest;
     30   //不同的浏览器获取对象xmlhttprequest对象方法不一样
     31   if(window.ActiveXobject)
     32   {
     33       xmlHttpRequest=new ActiveXobject("Microsoft.XMLHTTP");
     34   }
     35   else
     36   {
     37         xmlHttpRequest=new XMLHttpRequest();
     38   }
     39   return xmlHttpRequest;
     40   }
     41  
     42  //新建myXmlHttpRequest对象
     43  var myXmlHttpRequest="";
     44   
     45   function getCities(){
     46   //创建对象
     47       myXmlHttpRequest=getXmlHttpObject();
     48        // window.alert(myXmlHttpRequest);
     49       //如果创建成功,则进行post请求
     50       if(myXmlHttpRequest){
     51       //创建url
     52       var url="/ajax/showCities";//post
     53       //携带的参数
     54       var data="province="+$('sheng').value;
     55       //
     56       myXmlHttpRequest.open("post",url,true);
     57       //必填
     58       myXmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
     59       //指定回调函数
     60             myXmlHttpRequest.onreadystatechange=chuli;
     61       //发送请求
     62       myXmlHttpRequest.send(data);
     63       
     64       }
     65       
     66       
     67   }
     68   
     69   function chuli(){
     70       if(myXmlHttpRequest.readyState==4){
     71            // var mes=    myXmlHttpRequest.responseText;
     72       /* window.alert(mes);
     73       var mes_obj=eval("("+mes+")");
     74       window.alert(mes_obj);
     75       window.alert(mes_obj.ins[0].city); */
     76       // $('myres').value=mes_obj.info;
     77       
     78       
     79    //取出xml格式数据
     80            if(myXmlHttpRequest.status==200)
     81           {          
     82               //取出服务器回送的数据
     83               window.alert(myXmlHttpRequest.responseXML);
     84               var cities= (myXmlHttpRequest.responseXML.getElementsByTagName("city"));
     85               //window.alert(cities.length);
     86               //alert(cities[1].lastChild.nodeValue);
     87               for(var i=0;i<cities.length;i++)
     88               {alert(cities[i].childNodes[0].nodeValue);}
     89           } 
     90       
     91       }
     92       
     93   }
     94   
     95   
     96    function $(id)
     97   {
     98   return document.getElementById(id);
     99   }
    100   
    101   </script>
    102   
    103   
    104     This is my JSP page. <br>
    105     
    106     <select id="sheng" onchange="getCities();">
    107     <option value="">---省---</option>
    108     <option value="zhejiang">浙江</option>
    109     <option value="jiangsu">江苏</option>
    110     </select>
    111     
    112     <select id="city" onchange="sendRequest();">
    113     <option value="">--城市--</option>
    114     </select>
    115     
    116      <select id="country" onchange="sendRequest();">
    117     <option value="">--县城--</option>
    118     </select>
    119     
    120   </body>
    121 </html>

    3.text格式

    servlet 格式

     1 package com.hsp.action;
     2 
     3 import java.io.IOException;
     4 import java.io.PrintWriter;
     5 
     6 import javax.servlet.ServletException;
     7 import javax.servlet.ServletOutputStream;
     8 import javax.servlet.annotation.WebServlet;
     9 import javax.servlet.http.HttpServlet;
    10 import javax.servlet.http.HttpServletRequest;
    11 import javax.servlet.http.HttpServletResponse;
    12 
    13 /**
    14  * Servlet implementation class registerServlet
    15  */
    16 @WebServlet("/registerServlet")
    17 public class registerServlet extends HttpServlet {
    18     private static final long serialVersionUID = 1L;
    19        
    20     /**
    21      * @see HttpServlet#HttpServlet()
    22      */
    23     public registerServlet() {
    24         super();
    25         // TODO Auto-generated constructor stub
    26     }
    27 
    28     /**
    29      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
    30      */
    31     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    32         // TODO Auto-generated method stub
    33     
    34     //接受数据
    35         //String username=request.getParameter("username");
    36         //System.out.println(username);
    37         String infoString="";
    38         if ("shunping".equals("")) {
    39             infoString="用户名不可用";
    40         }
    41         else {
    42             infoString="用户名可用";
    43 
    44         }
    45         //返回文本数据  
    46        // response.setContentType("text/;charset=utf-8");  
    47        //返回xml格式文件
    48         response.setContentType("text/xml;charset=utf-8");  
    49 
    50         response.setHeader("Cache-Control", "no-cache");
    51         
    52         
    53         //返回xml 格式数据
    54         PrintWriter out=response.getWriter();
    55         StringBuilder builder=new StringBuilder();
    56        // builder.append("<message>");
    57        // builder.append(infoString).append("</message>");
    58         
    59       //  builder.append( "{"+'"'+"info"+'"'+":"  ).append('"'+infoString+'"'+"}");
    60         builder.append(infoString);
    61         out.println(builder.toString());
    62         
    63         //返回text格式数据
    64 //        ServletOutputStream outputStream = response.getOutputStream();  
    65 //        outputStream.write(infoString.getBytes("utf-8"));  
    66 //        //outputStream.write(pwd.getBytes("utf-8"));  
    67 //        outputStream.flush();  
    68 //        outputStream.close();  
    69     }
    70 
    71     /**
    72      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
    73      */
    74     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    75         // TODO Auto-generated method stub
    76         doGet(request, response);
    77     }
    78 
    79 }

    jsp格式

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'index.jsp' starting page</title>
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
      </head>
      
      <body>
      <script type="text/javascript">
      
      //创建ajax引擎
      function getXmlHttpObject(){
      var xmlHttpRequest;
      //不同的浏览器获取对象xmlhttprequest对象方法不一样
      if(window.ActiveXobject)
      {
          xmlHttpRequest=new ActiveXobject("Microsoft.XMLHTTP");
      }
      else
      {
            xmlHttpRequest=new XMLHttpRequest();
      }
      return xmlHttpRequest;
      }
      
      
      var    myXmlHttpRequest=null;
      //验证用户名是否存在
      function checkName()
      {
      
         myXmlHttpRequest=getXmlHttpObject();
          
      //    window.alert(myXmlHttpRequest);
     
     if(myXmlHttpRequest ){
      //    window.alert("创建成功");
          //通过myXmlHttpRequest对象发送请求到服务器的某个页面
          //1.第一个参数表示请求的方式,"get"/"post"
          //2.第二个参数指定url,对哪个页面发出ajax请求(本质仍然是http请求)
          //3.第三个参数 true表示使用异步机制,如果false,表示不使用异步
           var url="/ajax/registerServlet?mytime="+new Date()+"&username="+$("username").value
          //打开请求
          myXmlHttpRequest.open("post",url,true);
          //window.alert(url);
          //指定回调函数,chuli  是函数名
          myXmlHttpRequest.onreadystatechange=chuli;
          //真的发送函数,如果是get请求,则填入null即可
          //如果是post请求,则填入实际的数据
          myXmlHttpRequest.send(null); 
          
          
          }
     
          
      }
      
      //回调函数
       function chuli(){
      //window.alert("处理函数被调用"+myXmlHttpRequest.readyState);
      //取出从serlet返回的数据
       if(myXmlHttpRequest.readyState==4)
          {
          //取出值,文本格式
         //window.alert("服务器返回"+myXmlHttpRequest.responseText)
     //
     //window.alert( "xml:"+myXmlHttpRequest.responseXML);
      //获取message节点
     // var mes=myXmlHttpRequest.responseXML.getElementsByTagName("message");
      //window.alert(mes.length);
      //取出message节点
      //es[0]-->表示取出第一个message节点
      //childNodes[0]表示message节点的第一个子节点
     // var mes_val=mes[0].childNodes[0].nodeValue;
      //window.alert(mes_val);
     // ${'myres'}.value= mes_val;
          //$('myres').value=myXmlHttpRequest.responseText;
      /* var mes=    myXmlHttpRequest.responseText;
          window.alert(mes);
          var mes_obj=eval("("+mes+")");
          //window.alert(mes_obj.info);
           $('myres').value=mes_obj.info;
           */
            var mes=    myXmlHttpRequest.responseText;
           
                 $('myres').value=mes;
          
          } 
      }
        
      function $(id)
      {
      return document.getElementById(id);
      }
       
      
      
      
     
       
      
      
      
      
      
      
      
      
      
     
      </script>
      
      
        This is my JSP page. <br>
        <form action="???" method="post">
        
        用户名:<input type="text"name="username1" onkeyup="checkName();" id="username">
        <input type="button" onclick="checkName();" value="验证用户名">
      <input style="border- 0;color: red" type="text" id="myres"><br>
        用户密码:<input type="password" name="password"><br>
        电子邮件:<input type="text" name="email"><br>
        <input type="submit" value="用户注册"> 
        </form>
        
        
        
      </body>
    </html>
  • 相关阅读:
    360云盘、百度云、微云……为什么不出 OS X(Mac 端)应用呢?(用户少,开发成本高)(百度网盘Mac版2016.10.18横空出世)
    其实 Dropbox 的缺点也很明显,速度慢,空间小(我对国内的网盘的建议)
    为什么百度云、360云盘等都取消了同步盘功能?
    验证API
    操作系统进程压榨案例
    查询功能
    JavaScript 动画库和开发框架
    指针
    Attribute Routing
    自定义验证特性
  • 原文地址:https://www.cnblogs.com/albertfg/p/8031599.html
Copyright © 2011-2022 走看看