直接上例子!
第一例:$.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>
点击后的结果:张三:李四:王五:
----------------------------------------------------
第三例: