欢迎来到代码驿站!

JavaScript代码

当前位置:首页 > 网页前端 > JavaScript代码

ajax动态加载json数据并详细解析

时间:2021-11-02 09:56:42|栏目:JavaScript代码|点击:

效果图

jsp代码

<form >
   姓名:<input name="name" type="text"/>
   年龄:<input name="age" type="text"/>
   <input type="button" class="get" value="get提交"/>
   <input type="button" class="post" value="post提交"/>
   <input type="button" class="ajax" value="ajax提交"/>
   </form>
   <div id="box"></div>

servlet代码

//get
public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

  response.setContentType("text/html");
  response.setCharacterEncoding("utf-8");
  response.setContentType("text/html;charset=utf-8");
  String name = request.getParameter("name");
  String age = request.getParameter("age");
  if (name == null || name == "") {
   name = "测试名字admin";
  }

  if (age == null || age == "") {
   age = "测试年龄100";
  }
  user user = new user(1, name, age);
  PrintWriter out = response.getWriter();

  JSONObject jsonObj = JSONObject.fromObject(user);

  out.print(jsonObj);

  out.flush();
  out.close();
 }
//post
public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

  // response.setContentType("text/html");

  request.setCharacterEncoding("utf-8");
  response.setCharacterEncoding("utf-8");
  response.setContentType("text/html;charset=utf-8");
  String name = request.getParameter("name");
  if (name == null || name == "") {
   name = "测试名字admin";
  }
  String age = request.getParameter("age");
  if (age == null || age == "") {
   age = "测试年龄100";
  }
  user user = new user(1, name, age);
  PrintWriter out = response.getWriter();

  JSONObject jsonObj = JSONObject.fromObject(user);

  out.print(jsonObj);

  out.flush();
  out.close();
 }

JS核心代码

<script type="text/javascript">
  //get
 $(document).ready(function() {
  $('form .get').click(function() {
   $.get('ajaxServlet',function(response,status,xhr){
    var dataObj = eval("(" + response + ")");
    $("#box").html(response);
    alert(dataObj.name);

  });

 });
 //post
 $('form .post').click(function() {
   $.post('ajaxServlet',function(response,status,xhr){
    var dataObj = eval("(" + response + ")");
    $("#box").html(response);

  });

 });
 //ajax
 $('form .ajax').click(function() {
  alert($("[name='name']").val());
    $.ajax({
    type:'get',
    url:'ajaxServlet',
    data:{
    name:$("[name='name']").val(),
    age:$("[name='age']").val()
    },
    success:function(response, status, xhr){
    $("#box").html(response);}
    });

 });

 });

</script>

上一篇:Javascript实现通过选择周数显示开始日和结束日的实现代码

栏    目:JavaScript代码

下一篇:详解微信小程序 wx.uploadFile 的编码坑

本文标题:ajax动态加载json数据并详细解析

本文地址:http://www.codeinn.net/misctech/182176.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有