码迷,mamicode.com
首页 > Web开发 > 详细

ajax 异步请求,json前台后台交互

时间:2018-02-11 00:09:43      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:pre   后台   tps   throws   coding   交互   response   客户端   test   

直接上例子!

第一例:

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前台后台交互

标签:pre   后台   tps   throws   coding   交互   response   客户端   test   

原文地址:https://www.cnblogs.com/pxffly/p/8440068.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!