zoukankan      html  css  js  c++  java
  • ajax 异步请求,json前台后台交互

    直接上例子!

    第一例:$.getJSON()

    1.导入json的相关jar包

    2.后台servlet代码

    public class ajaxtest extends HttpServlet {
    
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            request.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=utf-8");
         //上面是处理乱码的 String[] str
    = {"张三","李四","王五"}; //最普通的json数组结构 JSONArray json = JSONArray.fromObject(str); //string转json结构 PrintWriter out = response.getWriter();   out.print(json); //response 将json输出到客户端。
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request, response);
    }
    }

    前端jsp页面

    <script type="text/javascript"
        src="http://libs.cdnjs.net/jquery/3.2.1/jquery.js"></script>
    
    <script type="text/javascript">
    $(document).ready(function(){
      $("#b01").click(function(){
          $.getJSON("${pageContext.request.contextPath}/ajaxtest",function(result){
              $.each(result,function(i,field){
                  $("#myDiv").append(field+":");
              });
          });
      });
      });
    </script>
    
    
    
    </head>
    
    <body>
    
    <div id="myDiv"><h2>通过 AJAX 改变文本</h2></div>
    <button id="b01" type="button">改变内容</button>

    点击按钮的结果:张三:李四:王五。

    ----------------------------------------------------------

    第二例 :$.ajax()

      后台 servlet不变

    jsp前端页面:

    <script type="text/javascript">
    $(document).ready(function(){
      $("#b01").click(function(){
          $.ajax(
          {
              url:"${pageContext.request.contextPath}/ajaxtest",
              dataType:"json",
              success:function(result){
                  $.each(result,function(i,fireld){
                      $("#myDiv").append(fireld+":");
                  });
              }
          });
      });
      });
    </script>
    </head>
    <body>
    <div id="myDiv"><h2>通过 AJAX 改变文本</h2></div>
    <button id="b01" type="button">改变内容</button>

    点击后的结果:张三:李四:王五:

    ----------------------------------------------------

     第三例:

  • 相关阅读:
    每日总结2021.9.14
    jar包下载mvn
    每日总结EL表达语言 JSTL标签
    每日学习总结之数据中台概述
    Server Tomcat v9.0 Server at localhost failed to start
    Server Tomcat v9.0 Server at localhost failed to start(2)
    链表 java
    MVC 中用JS跳转窗体Window.Location.href
    Oracle 关键字
    MVC 配置路由 反复走控制其中的action (int?)
  • 原文地址:https://www.cnblogs.com/pxffly/p/8440068.html
Copyright © 2011-2022 走看看