jquery Ajax example of passing array parameters to the background

Source: Internet
Author: User
Tags json getv
In JS to pass the array parameters to the background, if the array is placed in the object type, passed to the background is only the object string--[object objects, the specific reasons and solutions are as follows, there are similar problems friends can refer to the next

Requirements:
Passing array parameters to the background in JS

Analysis:
The arrays in JS are weakly typed and can put any type (object, base type), but if the array is an object type, passing to the background is only the object string--[object objects, for the following reasons:
In the background receive, can only use request to receive, Request.getparametervalues () method return is a string[], so, should be in the foreground transmission when the object's ToString () method is called, So what if you still want to pass the object? Cold!
However, you can use a JSON string to parse the JSON string into a Java object in the background.

Perhaps, you have to say, if it is a composite object, such as the following:

Copy Code code as follows:


public class Person {


private String username;


private String password;


private address addr;


}


There is an address type addr attribute in the person object, and it doesn't matter that the property values that are used by any object are basic data types, and only need to use the corresponding wrapper type parseint, or parsexxx parsing.

implementation:
OK, that's the way it works. First look at JS how to write:

Copy Code code as follows:


var as = [];


var temp = [];


for (var int = 0; int < 5; int++) {


Temp.push (' {"K": ');


temp.push (int);


Temp.push (', "V": ');


temp.push (int);


temp.push ('} ');


As.push (Temp.join (""));


}


//jquery in the method, specific reference to the jquery API


$.post (


"Servlet/ajaxservlet?m=putwarningrule", {"AA": as}


);


 


The final string is the following style, (just for example)

Copy Code code as follows:


{"K": 0, "V": 0}


Background receive, do not discuss any frame, only need httpservletrequest can

Copy Code code as follows:


string[] Jsonarr = Request.getparametervalues ("aa[]");


There is a point to note that the parameters in JS when the parameter called "AA", and in the background to receive the time is "aa[]", here should be the conversion of jquery, so the best way is in JS to be changed to "aa[]", the reason here did not write "[]" is to illustrate the problem. You can print all the parameters in the request by using the following methods

Copy Code code as follows:


enumeration<string> names = Request.getparameternames ();


while (names.hasmoreelements ()) {


string = (string) names.nextelement ();


System.out.println (string);


}


OK, so far, has been received, and the rest is how to turn a JSON string into a pojo. I use Jsontools-core-1.7.jar, this jar package relies on Antlr-2.7.7.jar, download itself to the code base, download, import classpath, write a simple tool class, there are 2 methods:

Copy Code code as follows:


/**


* Converts an object to a JSON-formatted string


* @param obj


* @return Returns the JSON string


*/


public static String tojsonasstring (Object obj) {


try {


return Jsonmapper.tojson (obj). render (FALSE);


} catch (Mapperexception e) {


E.printstacktrace ();


}


return null;


}





@SuppressWarnings ("unchecked")


public static <T> T jsontoobject (String jsonstr, class<t> targetclass) throws Tokenstreamexception, Recognitionexception, mapperexception{


Jsonvalue jv = new Jsonparser (new StringReader (JSONSTR)). NextValue ();


return (T) Jsonmapper.tojava (Jv,targetclass);


}





//test


public static void Main (string[] args) throws Exception {


person p = new person ();


P.SETK ("a");


P.setv ("V");





String json = tojsonasstring (p);


person NP = Jsontoobject (Json,person.class);


System.out.println (NP.GETK () + "= =" +np.getv ());


}


When request takes a value, it iterates through the array and converts

Copy Code code as follows:


person p = jsonutils.jsontoobject (jsonarr[0], person.class);


The person class is as follows:

Copy Code code as follows:


public class Person {
Private String K;
Private String v;
Public String getk () {
return k;
}
public void Setk (String k) {
this.k = k;
}
Public String Getv () {
return v;
}
public void Setv (String v) {
this.v = v;
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.