简体   繁体   English

尝试在servlet中获取数组时获取null

[英]Getting null in when trying to get array in servlet

I have a below set of code to get the table data in an array and pass the same to servlet through ajax call. 我有下面的代码集来获取数组中的表数据,并将其通过ajax调用传递给servlet。 But i am getting null. 但我越来越空了。 Please someone help me on what my mistake / how to get the required data since i am new to this servlet and web app. 由于我是这个servlet和Web应用程序的新手,请有人帮助我解决我的错误/如何获取所需的数据。 So far i tried with some examples given in SO. 到目前为止,我尝试使用SO中给出的一些示例。 but i am clueless to get my expected data. 但是我一无所获。

 var myTableArray = [];
        $("table#itemtable tr").each(function() { 
            var arrayOfThisRow = [];
            var tableData = $(this).find('td');
            if (tableData.length > 0) {
                tableData.each(function() { arrayOfThisRow.push($(this).text()); });
                myTableArray.push(arrayOfThisRow);
            }
        });

        alert(myTableArray); 
        $.ajax({
            url:"insertmasteritem",
            type:"POST",
            dataType:'json',
            data: {json:myTableArray},
            success:function(data){
                // codes....
           },
       });

Servlet code Servlet代码

String[] myJsonData = request.getParameterValues("json[]");
System.out.println("myJsonData.length"+myJsonData.length);

    for (int i = 0; i < myJsonData.length; i++) {

           String[] innerArray=myJsonData[i].split(",");  
           System.out.println(myJsonData[i]);
       }

Send your Json data like this 像这样发送您的Json数据

   $.ajax({
            url:"insertmasteritem",
            type:"POST",
            dataType:'json',
            data:myTableArray,
            success:function(data){
                // codes....
           },
   });

and In Servlet Class 和在Servlet类中

JSONObject jsonObj= new JSONObject(request.getParameter("myTableArray"));
Iterator it = jsonObj.keys(); 

while(it.hasNext())
{
  String jsonKey = (String)it.next();
  String jsonValue = jsonObj.getString(jsonKey);
  System.out.println(jsonKey  + " --> " + jsonValue );
}

Well, you need to send a properly formatted JSON object (as a string) to the servlet. 好吧,您需要将正确格式的JSON对象(作为字符串)发送到Servlet。 Possibly the easiest way to do this is to create some javascript objects and fill an array with these objects. 可能最简单的方法是创建一些javascript对象,并用这些对象填充数组。 The array data should then be converted to a JSON string (using JSON.stringify). 然后应将数组数据转换为JSON字符串(使用JSON.stringify)。 I'm going to hardcode object values (but you will get them from your table) 我将对对象值进行硬编码(但您将从表中获取它们)

Javascript code JavaScript代码

function generateJson(){
  var myObjArr = [];
//you will typically have just one object (e.g. myObj, which you will fill  in your ajax table loop 
  //myObj.v1 = v1_val;
  //myObj.v2 = v2_val;
  ...
  //myObjArr[i] = myObj; //
  myObj1 = { "v1": "Orange", "v2": "ABC", "v3":10,"v4":"OK"  };
  myObj2 = { "v1": "Apple", "v2": "XYZ", "v3":25,"v4":"OK"  };

  myObjArr[0] = myObj1;
  myObjArr[1] = myObj2;

 var jsonObjStr = JSON.stringify(myObjArr);
 //you can now use jsonObjStr to send your data to the servlet
 // document.getElementById("json").innerHTML = jsonObjStr;//this is just added for testing purposes
 }

The generated JSON 生成的JSON

[{"v1":"Orange","v2":"ABC","v3":10,"v4":"OK"},{"v1":"Apple","v2":"XYZ","v3":25,"v4":"OK"}]

As you can see, the json string starts with a [ (which denotes an array). 如您所见,json字符串以[(表示数组)开头。 You may have to change this to start with a { (and with a } ) depending on how your JSON parser works ({} denote an object). 您可能必须更改此名称才能以{(和})开头,具体取决于JSON解析器的工作方式({}表示对象)。

For the servlet part, it depends on the actual JSON parser you're using. 对于servlet部分,它取决于您使用的实际JSON解析器。 Try to use some of the suggestions provided by others. 尝试使用其他人提供的一些建议。 I can provide some code using Jackson though, but you will have to add the Jackson library to your classpath. 我可以使用Jackson来提供一些代码,但是您必须将Jackson库添加到您的类路径中。

为什么将参数值作为JSON []

String[] myJsonData = request.getParameterValues("json[]");

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

相关问题 尝试使用javaScript调用Servlet操作时获取Null - Getting Null when trying to Call Servlet action using javaScript Javascript - 尝试获取数组的原型时出现“未定义” - Javascript - Getting 'undefined' when trying to get array's prototype Servlet中的数组为null - Array in servlet as null 在尝试将ajax调用上的可序列化数据发送到servlet时,将响应作为“servlet临时移动” - getting the response as “servlet temporarily moved ” when trying to send serializable data on ajax call to a servlet 尝试获取平均评分时出现错误模板助手中的异常:TypeError:无法读取null的属性“ rating” - getting error when trying to get average rating Exception in template helper: TypeError: Cannot read property 'rating' of null Node.js Express | 尝试获取JSON时始终为null - Node.js Express | Always getting null when trying to get a JSON 尝试通过Yii2中的javascript获取自动填充文本框时获取空值 - Getting null value when trying to get autofull textbox through javascript in Yii2 尝试推送到数组时收到错误消息 - Getting an error message when trying to push to an array 尝试获取jquery对话框内的文本框的值时得到“ null” - getting “null” while trying to get the value of textbox that is inside a jquery dialog 尝试在localStorage中获取对象专有性时获取null - Getting null while trying to get an object propriety inside localStorage
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM