Struts2+jquery implement Ajax and return JSON type data __ garbled problem

Source: Internet
Author: User

The main implementation steps are as follows:

1. JSP pages use scripting code to execute AJAX requests

2, action query out the need to return the data, and converted to JSON type pattern data

3. Configure Struts.xml Files

4, the page script accepts and processes the data

The key is as follows several points

1. Introduction of the package: Struts2 to the data JSON serialization, you must use the Struts2 json-lib,struts2-json-plugin package;

2.json Data Processing: The asynchronous submissions are in JSON format and struts2-json-plugin the data for JSON processing, so the extends of package nodes in the STRUTS2 configuration file struts.xml must be: Extends= "Json-default";

For example:<package name= "Default" namespace= "/test" extends= "Json-default" >

3. Similarly, because of the return of JSON data, the type of result must also use JSON;

Note: Struts2 can only introduce the Json-lib,struts2-json-plugin package when the type attribute of result sets JSON to not error:

<result type= "JSON" >
<param name= "Root" >result</param>
<!--result is the variable name that is set in the action and the data that the page needs to be returned, and the variable must have a setter and getter method-->
</result>

4. For asynchronous commits, the result node value of the action should be null, that is, it cannot be shifted (for example: only <result name= "UserInfo" type= "JSON" ></result>);

1, first look at the JSP page

Page effects

Do a provincial and county village five level of the regional Drop-down list, first enter the page to load all provinces page code:

$ (function () {
             var pid = "000000000000";
	    	 $.ajax ({  
	            URL: "getregionbranch.action",  
	            type: "POST",  
	            data: "pid=" + PID,  
	            dataType: "JSON"  
	            , Success:function (data) {  
	            $.each (data,function (i,item) {
	                    $ ("#province"). Append ("<option value=" + item.id + ">" + item.pcctvname + "</option>");//Assignment  
	                };  
	  
	            },
	            error:function (XHR, status, error) {
							 alert (status);  
	                         alert (xhr.responsetext); 
						} Do not add "," 
	         }) 
    
2, the action queries out the data that needs to be returned and converts to the JSON type pattern data as follows

/**
	 * Access to the five-level data of the district, province, county and township
	 * @return
	 * @throws Exception
	 /public
	String getregion () throws exception{< C5/>this.getrequestandresponse ();
		String pid =request.getparameter ("pid");
		List<region> Region =branchservice.getregion (PID);
		Regionlist = jsonarray.fromobject (region);
		return SUCCESS;
	}

3, configure the Struts2.xml file

First put

<package name= "Struts1" extends= "Struts-default" namespace= "/" >  

To

<package name= "Struts1" extends= "Json-default,struts-default" namespace= "/" >  
This will allow you to return the JSON data.


        <!--branch management   -->
	<action name= "*branch" class= "com.action.BranchAction"  method= "{1}" >
		<result type= "JSON" > 
		    <param name= "root" >regionList</param>
		</result>  
	        < Result name= "List" >/admin/branch/branch_list.jsp</result>
	        <result name= "edit" >/admin/branch/ Branch_edit.jsp</result>
	</action>
		  
4, the page receives processing data

                $.each (Data,function (i,item) {
	             $ ("#province"). Append ("<option value=" + item.id + ">" + item.pcctvname + " </option> ");//Assign Value  
	          });  
	  
Here is the data that is processed after the list type is converted to JSON, and the Drop-down list of assigned values to select is recycled.

There is also a data that returns a bean converted to JSON, for example:

Success:function (data) { 
   Jsonobject json = jsonobject.fromobject (user)://Convert Map object to JSON type data result
   = Json.tostring ()//Assign value to result, pass to page
}
Result declares get (), set () method.

Then the foreground handles the data like this:

   Success:function (data) {
        var d = eval ("(" +data+ ")")//Convert data to JSON type, you can output it with alert () to see what kind of structure
        The resulting d is a shape such as {"Key": "Value", "Key1": "Value1"} of the data type, and then takes the value out of

        alert (d.name);

        alert (d.age);
 }

Note: The eval () method is used only if you need to convert to a JSON object when you return a string, and if you have specified in Ajax that returns datatype as JSON, there is no need to use this method, and it is recommended that you use the data returned directly.

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.