1. 程式人生 > >java+jquery+json+ajax非同步獲取資料

java+jquery+json+ajax非同步獲取資料

專案開發中,很多時候需要使用ajax+json來獲取伺服器資料, 同時伺服器也會採用返回json資料以達到跨平臺訪問的形式:
我們利用sturts2 完成一個demo,自行搭建struts2的環境:
1、實體類:

  import java.util.Date;


public class Role {

    private int id;
    private String name;
    private String createDate;

    public Role(){}

    public Role(int id, String name, String createDate) {
        super
(); this.id = id; this.name = name; this.createDate = createDate; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this
.name = name; } public String getCreateDate() { return createDate; } public void setCreateDate(String createDate) { this.createDate = createDate; } }

2、struts2 action實現

package com.xingxue.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util
.Date; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONObject; import org.apache.struts2.ServletActionContext; import com.xingxue.model.Role; public class RoleAction { public String getData() { HttpServletResponse response = ServletActionContext.getResponse(); try { PrintWriter out = response.getWriter(); Role role = new Role(1,"財務",new Date().toString()); JSONObject jsonStr = JSONObject.fromObject(role); String str = jsonStr.toString(); out.print(str); out.flush(); out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }

3、js獲取資料實現:

package com.xingxue.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;

import com.xingxue.model.Role;

public class RoleAction {

    public String getData() {

        HttpServletResponse response = ServletActionContext.getResponse();
        try {
            PrintWriter out = response.getWriter();

            Role role = new Role(1,"財務",new Date().toString());

            JSONObject jsonStr = JSONObject.fromObject(role);
            String str = jsonStr.toString();
            out.print(str);
            out.flush();
            out.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }

}