Struts2 + jquery + JSON Ajax technology

Source: Internet
Author: User

Step 1: import the package and add the JSON plug-in of struts2 to the lib and jsonplugin of the web Project:Http://code.google.com/p/jsonplugin/downloads/list
Step 2: Add a package for Ajax in struts. xml

<Package name = "ajax" extends = "JSON-Default">
<Action name = "ajaxrequest"
Class = "org. David. struts2.helloworld">
<Result type = "JSON"> </result>
</Action>
</Package>
Note: JSON-default has inherited Struts-default.

Step 3: Use js to display data

<SCRIPT type = "text/JavaScript" src = "JS/jquery-1.4.2.min.js"> </SCRIPT>
<% @ Taglib prefix = "S" uri = "/Struts-tags" %>
<SCRIPT type = "text/JavaScript">
Function clickbutton ()
{
VaR url = 'ajaxrequest. action ';
VaR Params = {
Name: $ ('# name'). ATTR ('value ')
};
Jquery. Post (URL, Params, callbackfun, 'json ');
}
Function callbackfun (data)
{
VaR BB = data. listarticles; // corresponds to the Message attribute of the helloworld class
For (I = 0; I <BB. length; I ++ ){
If (BB [I]. Title. = '1 '){
Alert ('already exist ')
}
}
// Render the page after obtaining data
}
</SCRIPT>

Note: // listarticles is the returned list type, which is the same as the array type. Here, the object of the array returned by. length is,

Bb [I]. Title. = '1' the title of the returned object,

Step 4: code in action

Private string name;

Private list <Article> listarticles;

Get Set Method

@ Override
Public String execute () throws exception {
Listarticles = This. articleservice. findallarticle ();
Return success;
}

Note: articleservice cannot have the get method (Spring dependency injection) but can only have the set method.

Step 5: code in JSP

<Input id = "name" type = "text">
<Input type = "button" value = "OK" onclick = "javascript: clickbutton ();">

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.