1

In My.htm, I post a array var mytemp to server side, I hope to retrieve the array var in server side.

I only get the a string D 1,D,2,Tom'Dog if I use the following code, how can I retrieve the array in server side ? Thanks!

BTW, I hope to do a full post, not ajax, so I think that $.ajax() doesn't fit.

My.htm

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>

    <script src="js/jquery1.10.2.min.js?isassets=1" type="text/javascript"></script>

    <script type="text/javascript">

     $(function () {
        document.querySelector('#myformID').addEventListener('submit', event => {
           if (!confirm('Do you want to delete selected images?')) {
              event.preventDefault();
           }
        });

        $("#myformID").submit( function(eventObj) {

         var mytemp=new Array();
          mytemp.push("D 1");
          mytemp.push("D,2");
          mytemp.push("Tome'Dog");


           $('<input />').attr('type', 'hidden')
              .attr('name', "myCw")
              .attr('value',mytemp)
             .appendTo('#myformID');
           return true;
        });

     });

    </script>


</head>

<body>
   <div id="container">
       <form action='' method='post' enctype='multipart/form-data' id="myformID">           
           <input type='file' name='myfilename' /> Please select a file
           <input type='submit'name='submit' value='Delete Selecetd Items' />
       </form>

    </div>

</body>
</html>

Server Side

public class HttpServer extends NanoHTTPD {

   private Context mContext;

   public HttpServer(Context myContext) throws IOException {
        super(PublicParFun.GetWebPort(myContext));
        this.mContext=myContext;
        start(NanoHTTPD.SOCKET_READ_TIMEOUT);
   }


    private Response POST(IHTTPSession session) {
         Utility.LogError("Handle Post");

        try {
            Map<String, String> files = new HashMap<String, String>();
            session.parseBody(files);


            Set<String> keys1 =session.getParms().keySet() ;
            for(String key: keys1){
                String name = key;
                String loaction =session.getParms().get(key);                
            }          

        } catch (Exception e) {
            Utility.LogError("This is an error "+e.getMessage() );
            System.out.println("i am error file upload post ");
            e.printStackTrace();
        }
        return newFixedLengthResponse(Response.Status.OK, NanoHTTPD.MIME_PLAINTEXT,"I'm Hello!");
    }




    @Override
    public Response serve(IHTTPSession session) {

        String uri = session.getUri();
        Method method = session.getMethod();

        MURLPar mURLPar=new  MURLPar(mContext);
        FileFolderHelper.SetMURLParValue(mURLPar,session);

        if (mURLPar.isassets.value!=null && mURLPar.isassets.value.equals("1")){
            return GetResponseInputByAssetsFile(uri);
        }


        if (Method.POST.equals(method)) {      
            return POST(session);
        }


        String s=FileFolderHelper.GetStringTemplate(mContext,mContext.getString(R.string.WebImageBase));
        return newFixedLengthResponse(s);
    }
}

To Erfan Mowlaei: Thank you! Is the following code OK?

Client Side:

  var mytemp=new Array();
       mytemp.push("D 1");
       mytemp.push("D, 2");
       mytemp.push("D'3");


       $("#myformID").submit( function(eventObj) {
           $('<input />').attr('type', 'hidden')
              .attr('name', "myCw")
              .attr('value', JSON.stringify(mytemp))
             .appendTo('#myformID');
           return true;
      });

Server Side

 public ArrayList<String> jsonStringToArray(String jsonString) throws JSONException {

        ArrayList<String> stringArray = new ArrayList<String>();

        JSONArray jsonArray = new JSONArray(jsonString);

        for (int i = 0; i < jsonArray.length(); i++) {
            stringArray.add(jsonArray.getString(i));
        }

        return stringArray;
    }
HelloCW
  • 843
  • 22
  • 125
  • 310

1 Answers1

1

I assume what you are getting is either JsonObject or you should send JsonObject in order to be able to get it and convert it to array on server side. if you send the data in JsonArray form, you can get it like this in NanoServer:

@Override
public Response serve(IHTTPSession session) throws JSONException {
    //Log.e("Tag", "request received!");
    Map<String, String> files = new HashMap<String, String>();
    Method method = session.getMethod();
    if (Method.POST.equals(method) || Method.PUT.equals(method)) {
        try {
            session.parseBody(files);
        } catch (IOException ioe) {
            try {
                return new Response(Response.Status.INTERNAL_ERROR, MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                Log.e("UnsupportedEncodingException", e.getMessage());
            }
        } catch (ResponseException re) {
            try {
                return new Response(re.getStatus(), MIME_PLAINTEXT, re.getMessage());
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                Log.e("UnsupportedEncodingException", re.getMessage());
            }
        }
    }

    final JSONObject json = new JSONObject(files.get("postData"));
    //Log.e("MyData", json.toString());
    responseInterface.OnResponse(json); // my interface to pass data to other classes
    return newFixedLengthResponse("Success!");
}

Then later in responseInterface.OnResponse(JsonObject json); you can parse that data and make an array out of it.

M. Erfan Mowlaei
  • 1,376
  • 1
  • 14
  • 25
  • @HelloCW on which part do you need more code? Consider that I am android dev and I can help you as long as you ask in android part. – M. Erfan Mowlaei Nov 16 '16 at 07:33
  • final JSONObject json = new JSONObject(files.get("postData")) cause error – HelloCW Nov 16 '16 at 07:47
  • The code above was used to get Json params coming from IoT device, but I guess your case is similar, try finding how to post data in Json format using javaScript, if you send JsonObject from client sid, you should be able to get it on server side using the code I provided. – M. Erfan Mowlaei Nov 16 '16 at 07:51
  • Thank you! I have searched "how to post data in Json format using javaScript", but I can't get the correct result without ajax, could you write a sample html code to post array data in Json ? – HelloCW Nov 16 '16 at 09:42
  • Thanks! I have read your document ,I hope to do a full post, not ajax, what I need to post a array in client side, and retrieve the array in server side. how can I do? Thanks – HelloCW Nov 17 '16 at 01:09
  • @HelloCW If I am not mistaken you want to be able to click a button in HTML page and receive it in your app, then you need to look at this: http://stackoverflow.com/a/3472228/4260559 that way you can post from HTML and get it with your app, for posting you can look at this link: https://darobin.github.io/formic/specs/json/ and the code to receive JSON object is as I have given you – M. Erfan Mowlaei Nov 17 '16 at 06:44