java+jquery+json+ajax异步获取数据

本文介绍了一个使用Struts2结合Ajax和JSON技术的示例项目,通过具体代码展示了如何搭建Struts2环境并实现从服务器获取JSON数据的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目开发中,很多时候需要使用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;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值