直接上例子!
第一例:
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 异步请求,json前台后台交互
原文地址:https://www.cnblogs.com/pxffly/p/8440068.html