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 ();">