简体   繁体   English

在sling servlet中传递一个对象数组

[英]pass an array of objects in sling servlet

I have an array of objects. 我有一个对象数组。

var mydata1 = {};
var mydata2={};
mydata1.name="john";
mydata2.class="third";
mydata2.name="pan";
mydata3.class="second";
var dataArray= new Array();
dataArray[0]=mydata1;
dataArray[1]=mydata2;

in ajax call
  jQuery.ajax({
        url: '/myservlet',
        type: 'POST',
        data: dataArray,
        async: false,
        success: function(result) {
            alert("Saved Node.")
        },
        failure:function(result) {
            alert("Not Saved")
        }
    });

Objects are required to be made because the value in objects is dynamic.And will change in future.How to pass this kind of object through ajax. 需要创建对象,因为对象中的值是动态的。将来会改变。如何通过ajax传递这种对象。 Can we change into JSON. 我们可以改成JSON吗? But iteration in servlet is also required. 但是也需要在servlet中进行迭代。 Thanks in advance. 提前致谢。

Use JSON.stringify() function on the data array to serialize it to the JSON format: 在数据数组上使用JSON.stringify()函数将其序列化为JSON格式:

jQuery.ajax({
    url: '/myservlet',
    type: 'POST',
    data: JSON.stringify(dataArray),
    ...

Then you may read the JSON in the servlet using JSONArray : 然后你可以使用JSONArray读取servlet中的JSON:

String requestData = request.getReader().readLine();
JSONArray array = new JSONArray(requestData);
// to get name property of the first object:
array.getJSONObject(0).getString("name");

Created JSON will be just a single line of text, so we don't need to read more lines from the request reader. 创建的JSON只是一行文本,因此我们不需要从请求阅读器中读取更多行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM