从ajax字符串创建javascript数组。

时间:2012-10-09 10:39:02

标签: javascript servlets

var  data = [
        {lastName: "Dente", name: "Al"},
        {lastName: "Noring", name: "Constance"},
        {lastName: "Haas", name: "Jack"},
        {lastName: "Tress", name: "Matt"},
        {lastName: "Turner", name: "Paige"}
    ];

这是我要创建的javascript数组。如何从servlet发送此数据并在javascript中创建数组对象。

String dataString=/*prepare data */
response.getWriter().write(dataString);

如何在servlet中准备这个dataString以及如何在客户端中使用该字符串创建数组?

2 个答案:

答案 0 :(得分:2)

如果您有以下Java类:

public class Person {
    private String lastName;
    private String name;

    public Person(String lastName, String name) {
        this.lastName = lastName;
        this.name = name;
    }

    /* getters and setters */
}

然后,您可以使用Gson

通过以下方式轻松生成数据
List<Person> people = new ArrayList<Person>();

people.add(new Person("Smith", "John"));
people.add(new Person("Example", "An"));

String json = gson.toJson(people);

json变量的值为[{"lastName": "Smith", "name": "John"},{"lastName": "Example", "name": "An"}]

然后只需将其作为servlet的响应发送,请记住将请求的内容类型设置为application/json

为了处理JavaScript中的数据,我建议使用jQuery的.getJSON()方法,例如

$.getJSON('url of servlet', function (data) {
    console.log(data); // <-- data will be an Array containing two objects
});

答案 1 :(得分:1)

使用net.sf.json.JSONObject在服务器端

中实现此目的

了Serverside:

public class Data {
    String lastName;
    String name;
//......constructors,getters,setters
}

ArrayList<Data> serverData = new ArrayList<Data>();
serverData.add(new Data("Fred", "Flintstones"));
serverData.add(new Data("Wilma", "Flintstones"));
String jsonStr = JSONObject.fromObject(serverData);
response.getWriter().write(jsonStr);

在客户端使用JSON.parse

客户方:

function ajaxCallback(data) {
    var jObj = JSON.parse(data);
    for(var i in jsonObject)
    {alert(jObj[i].name+" "+jObj[i].lastName);}
}

希望这有帮助!