Example of passing array parameters to the background using jquery ajax

Source: Internet
Author: User
Tags getv

Requirements:
Passing array parameters to the background in JS

Analysis:
Arrays in JS are weakly typed and can be put in any type (object, basic type). However, if an array contains an object type, when passed to the background, only the object string -- [Object object] can be displayed, for the following reasons:
When receiving in the background, you can only use request to receive the request. the getParameterValues () method returns a String []. Therefore, the toString () method of the object is called during foreground transmission. What should I do if I still want to pass the object? Cool!
However, JSON strings can be used to parse JSON strings into JAVA objects in the background.

Maybe, what if it is a composite object, for example:
Copy codeThe Code is as follows:
Public class Person {
Private String username;
Private String password;
Private Address addr;
}

The Person object has an addr attribute of Address type. It doesn't matter. The final attribute values of any object are basic data types. You only need to use the corresponding packaging type parseInt or parseXXX for parsing.

Implementation:
OK, that's how it works. First, let's look at how to write javascript:
Copy codeThe Code is 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 (""));
}
// Methods in Jquery. For details, refer to Jquery API
$. Post (
"Servlet/AjaxServlet? M = putWarningRule ", {" aa ":}
);


The final string is the following style (for example only)
Copy codeThe Code is as follows:
{"K": 0, "v": 0}

Received in the background. No framework is discussed. You only need HttpServletRequest.
Copy codeThe Code is as follows:
String [] jsonArr = request. getParameterValues ("aa []");

It is worth noting that the parameter name is "aa" when passing parameters in js, but "aa []" when receiving parameters in the background. Here we should have converted Jquery, so the best way is to change it to "aa []" in JS. The reason why "[]" is not written here is to illustrate the problem. You can print all parameters in the request as follows:
Copy codeThe Code is as follows:
Enumeration <String> names = request. getParameterNames ();
While (names. hasMoreElements ()){
String string = (String) names. nextElement ();
System. out. println (string );
}

OK. So far, the receipt has been completed, and the rest is how to convert a JSON string into a POJO. I use jsontools-core-1.7.jar, this jar package depends on the antlr-2.7.7.jar, go to the code library to download, download, import classpath, write a simple tool class, there are mainly such two methods:
Copy codeThe Code is as follows:
/**
* Convert an object to a JSON string
* @ Param obj
* @ Return returns a 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 ("");
P. setV ("v ");

String json = toJSONAsString (p );
Person np = jsonToObject (json, Person. class );
System. out. println (np. getK () + "=" + np. getV ());
}

After the request obtains the value, it traverses the array and converts it one by one.
Copy codeThe Code is as follows:
Person p = JSONUtils. jsonToObject (jsonArr [0], Person. class );

The Person class is as follows:
Copy codeThe Code is 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.