Communication between jquery and struts2 using Ajax

Source: Internet
Author: User

Jquery has the following Ajax methods:
1. $. Post (URL, Params, callback );
2. $. getjson (URL, Params, callback );
3. $. Ajax ();
4. $. Load (URL, Params, callback );

First: Post is used for submission. Chinese parameters do not need to be transcoded. In callback, if you want to obtain a JSON string, you need to convert it.
For example:

$. Post (URL, {ID: ID, code: code, companyid: companyid}, function (data) {showcompanyradialdatalistdatalist}); this datalist is the list of data retrieved from the background. Function showcompanyradialdatalist (datalist) {var OBJ = eval (datalist);} // This eval can convert data into a JSON string. This facilitates subsequent values. For example: for (VAR I = 0; I <obj. length; I ++) {$ ("TD: eq (1)", fig [I]. nuclide); // The data in datalist can be retrieved in JSON format}

2nd Methods: getjson is submitted in get mode. Therefore, if your Params parameter contains Chinese characters, transcode it first. Otherwise, garbled code is submitted to the background.

$. Getjson (URL, Param, function (jsondata) {the returned jsondata can be directly retrieved without conversion. Example: jsondata [0]. Nuclide}

3rd Methods: $. Ajax, which is the most flexible.

$. Ajax ({URL: URL, // address data: data, // parameter type: 'post', // You can select post/get to recommend post async: false, // synchronous asynchronous ype: 'json', // return data type success: function (data) {accidentlist = data. list; // the data in the data can be directly retrieved here, because the return value is set to JSON. }});

Of course, there are many parameters in $. Ajax that can be added with more special effects, such as ajaxstart and ajaxstop,
The type, async, and ype parameters above are not required.
4th Methods: $. load is rarely used. It is generally used to load a page or XML.

Summary: If the parameter does not contain Chinese characters and you want to use JSON directly, $. getjson is recommended. If there is Chinese, $. Post or $. Ajax is used.

From above: http://pipe.iteye.com/blog/372394 #

However, there are various data transmission methods,

In the form of a key-Value Pair string: simple and convenient "param1 = value1 & param2 = value2"

In XML format: although it is a little troublesome, it can be used in case of data types with complex structures. For details, see: Click to open the link.

JSON: JSON is the native JavaScript format, which means that
JSON data processing in does not require any special APIs
Or toolkit. Click Open Link

However, it should be noted that jquery. js conflicts with JSON. js because of the $ symbol conflict...

1. There are jquery plug-ins on the Internet that convert JS objects and JSON
Jquery-JSON

Http://blog.csdn.net/mycup163/article/details/7090077

var thing = {plugin: 'jquery-json', version: 2.3};var encoded = $.toJSON( thing );// '{"plugin":"jquery-json","version":2.3}'var name = $.evalJSON( encoded ).plugin;// "jquery-json"var version = $.evalJSON(encoded).version;// 2.3

2. if you do not want to use JSON. JS can be like this... manually write JSON and click to open the link .. for JSON sent by the server, you can use jquery's eval ("(" + Data + ")")/$. convert parsejson () to a JavaScript Object

Finally to the server

In order to avoid the same problems in future development, we will record the problems.
Question about JSON-Struts Interaction
Front-end technology uses extjs:
Strut2 provides JSON-supported plug-ins
JSON-default and JSON-default must be inherited from Struts-default.
<Package name = "JSON" namespace = "/" extends = "JSON-Default">

<Action name = "moduleaction" class = "moduleaction">

<Result type = "JSON" name = "finddata">
<Paramname = "root"> datas </param>
<Paramname = "includeproperties"> success, totalcount </param>
</Result>

<Result type = "JSON" name = "findtree">
<Paramname = "root"> result </param>
</Result>
</Action>

1. After the type in the result is set to JSON, the container will automatically encapsulate the action attribute into a JSON object (which is implemented by the JSON interceptor), and then call the Ajax callback method to return json data.

2. includeproperties parameter: attribute value to be included in the output result. Here, the regular expression matches the attribute name. You can use "," to separate multiple regular expressions.
For example, <paramname = "includeproperties"> module. *, user \. Username </param> indicates all attributes of the module and user name.

3. excludeproperties parameter: attribute values to be excluded from output results. It also supports regular expressions to match attribute names. You can use commas (,) to separate multiple regular expressions, similar to includeproperties.

4. Why use the includeproperties or excludeproperties parameter:
It is mainly used to filter out the interface. pojo's set, list, and other objects do not need data to prevent other associated objects from being retrieved cyclically or the interface cannot be found.

If this parameter is not set, all attributes in the action are processed by default. If the action contains interface injection, the JSON interceptor may fail to find the interface and return the result,

In addition, if an object exists in the action, this object is associated with many objects. The JSON interceptor converts all the attributes of the associated objects to the JSON format,

If other objects include list and set, the returned results may be large, but they may not be returned due to an endless loop.

If you do not use <paramname = "includeproperties"> or other methods to filter JSON data, you can use DEBUG to find the JSON string returned by the foreground,

Converts all the attributes in the action into JSON strings and returns them to the client.

(Including the service interface, all pojo attributes, and associated pojo. Sometimes the results cannot be returned or an error is reported,

However, the front-end cannot execute the callbackfunction. This is mainly because the interface cannot be found or there are too many associated pojo, leading to an endless loop ),

The root, includeproperties, and excludenullproperties parameters are commonly used.

Of course, there are other methods, such as adding JSON annotations to the attributes of pojo.

5. The name attribute in the result tag indicates the name returned by the action class in struts2.
For example
Public String findallbyid () throws exception {
Int id = integer. parseint (this. Request. getparameter ("PID "));
List <modulebean> List = service. findbyid (ID );
Return "findtree ";
}
The above code return "findtree" will find the findtree result set, encapsulate it, and return JSON to the client

Therefore, action can be configured with multiple results.

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.