阅读(4157) (19)

JSP+jquery使用ajax方式调用json的实现方法

2016-08-16 13:45:57 更新

本文实例讲述了JSP+jQuery使用Ajax方式调用JSON的实现方法,在这里分享给大家以供大家参考,具体的实现以及代码如下所示:
前台:

<script type="text/javascript" src="jquery-1.5.1.min.js"></script>
<script type="text/javascript">
 //test
 function test(uid)
 {
  if(confirm("确定该用户操作"+uid+"吗?"))
  {
  var date = new Date();
  var param = {uid:uid};
  jQuery.get("test.jsp?para=" + date, param,
    function(data){
     if(data != null)
     {
    var result = data.result;
    //alert("data==="+data);
    if(result == 1)
    {
    alert("操作失败");
    }
    if(result == 0)
    {
    alert("操作失败。");
    //document.location.href = document.location;
    //window.location.reload();
    }
     }
  });
  }
 }
</script>
<a href="javascript:void(0);" onclick="test(111111111111111111);">submit</a>

后台:
test.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%
response.setContentType("application/x-json;charset=UTF-8");
String uid=request.getParameter("uid");
int ret=0;
String result = "{"result":" + ret + "}";
out.print(result);
%>

注意:返回json格式
如{"result":0}
需要设置 :

代码如下:

response.setContentType("application/x-json;charset=UTF-8");

jsp+jquery+ajax+json

Person、Address 2个类描述一个人,用ajax把数据取回显示在页面上,在DemoServlet里组装数据,项目用到的文件

json-lib-2.1-jkd15.jar

commons-lang-2.1.jar

commons-logging.jar

commons-collections-3.2.jar

commons-beanutils.jar

jquery.js

json.js

下面是详细代码:

Person:

public class Person implements java.io.Serializable{   
    private String name;   
    private String sex;   
    private Integer age;   
    private Address address;   
    public String getName() {   
        return name;   
    }   
    public void setName(String name) {   
        this.name = name;   
    }   
    public String getSex() {   
        return sex;   
    }   
    public void setSex(String sex) {   
        this.sex = sex;   
    }   
    public Integer getAge() {   
        return age;   
    }   
    public void setAge(Integer age) {   
        this.age = age;   
    }   
    public Address getAddress() {   
        return address;   
    }   
    public void setAddress(Address address) {   
        this.address = address;   
    }   
} 

Address:

public class Address implements java.io.Serializable{   
    private String province;   
    private String city;   
    private String country;   
    public Address() {   
    }   
    public Address(String province, String city, String country){   
        this.province =province;   
        this.city = city;   
        this.country = country;   
    }   
    public String getProvince() {   
        return province;   
    }   
    public void setProvince(String province) {   
        this.province =province;   
    }   
    public String getCity() {   
        return city;   
    }   
    public void setCity(String city) {   
        this.city = city;   
    }   
    public String getCountry() {   
        return country;   
    }   
    public void setCountry(String country) {   
        this.country = country;   
    }   
} 

DemoServlet:

import java.io.IOException;   
import java.util.ArrayList;   
import java.util.List;   
import javax.servlet.ServletException;   
import javax.servlet.http.HttpServlet;   
import javax.servlet.http.HttpServletRequest;   
import javax.servlet.http.HttpServletResponse;   
import net.sf.json.JSONArray;   
import net.sf.json.JSONObject;   
import org.wncnke.json.pojo.Address;   
import org.wncnke.json.pojo.Person;   
public class DemoServlet extends HttpServlet{   
    @Override 
    protected void doGet(HttpServletRequest request,HttpServletResponse response)   
            throwsServletException, IOException {   
        doPost(request, response);  
    }   
    @Override 
    protected void doPost(HttpServletRequest request,HttpServletResponse response)   
            throwsServletException, IOException {   
       response.setContentType("text/xml;charset=utf-8");   
        response.setHeader("Cache-Control","no-cache");   
           
        try{   
              
            Personperson1 = new Person();   
           person1.setName("小王");  
           person1.setSex("女");   
           person1.setAge(23);   
            person1.setAddress(newAddress("辽宁省","大连市","高新园区"));   
              
           List<Person> list = new ArrayList<Person>();   
           list.add(person1);   
              
            try{   
               //取集合   
               JSONArray jsonArray = JSONArray.fromObject(list);   
       
               JSONObject jsonObject = new JSONObject();   
                  
               jsonObject.put("person", jsonArray);   
                  
               response.getWriter().write(jsonObject.toString());    
                  
            } catch(IOException e) {   
               e.printStackTrace();   
           }   
              
        }catch(Exception e){   
           e.printStackTrace();   
        }   
    }   
}

web.xml:

<?xml version="1.0"encoding="UTF-8"?> 
<web-app xmlns="http://caucho.com/ns/resin" xmlns:resin="http://caucho.com/ns/resin/core"> 
       
    <display-name>json</display-name> 
       
    <welcome-file-list> 
       <welcome-file>index.jsp</welcome-file>        
    </welcome-file-list> 
     
    <servlet> 
       <servlet-name>DemoServlet</servlet-name> 
       <servlet-class>org.wncnke.json.servlet.DemoServlet</servlet-class> 
    </servlet> 
    <servlet-mapping> 
       <servlet-name>DemoServlet</servlet-name> 
       <url-pattern>/demoServlet</url-pattern> 
    </servlet-mapping> 
       
</web-app>

index.jsp:

view plaincopy to clipboardprint?
<%@ page language="java" pageEncoding="utf-8"%> 
<%   
String path = request.getContextPath();   
String basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
%> 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html> 
<head> 
<base href="<%=basePath%>"> 
<mce:script language="javascript" src="script/jquery.js"mce_src="script/jquery.js"></mce:script>     
<mce:script language="javascript" src="script/json.js"mce_src="script/json.js"></mce:script>    
<mce:script language="javascript"><!--   
      
function addPerson(){      
    $.getJSON("demoServlet",null,function call(data){   
        var list = data.person;   
        $.each(list, function(i, p){   
            var row =$("#tr").clone();   
           row.find("#name").text(p.name);   
           row.find("#age").text(p.age);   
           row.find("#sex").text(p.sex);   
           row.find("#address").text(p.address.province + p.address.city +p.address.country);   
           row.appendTo("#tbody");   
        });      
    });   
}      
// --></mce:script> 
</head> 
<body> 
<input type="button" value="JsonView"onClick="addPerson();">      
<div id="dateMessage">      
    <table id="planTable"border="1">      
        <tr> 
           <td>Name</td> 
           <td>Sex</td> 
           <td>Age</td> 
           <td>Address</td> 
       </tr>      
        <tbody id="tbody"> 
            <trid="tr"> 
               <td id="name"></td> 
               <td id="sex"></td> 
               <td id="age"></td> 
               <td id="address"></td> 
           </tr>      
        </tbody> 
    </table>      
</div> 
</body> 
</html>