欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-03-21 13:14:13
效果图 jsp代码
姓名: 年龄:&...

效果图

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

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>

以上这篇ajax动态加载json数据并详细解析就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

相关标签: ajax 加载 json