Integrate struts2 JSON with jquery to implement Ajax and user registration verification

Source: Internet
Author: User
Document directory
  • Overview
  • Parameters
  • Example

Asynchronous Communication is easy to implement with json and jquery.

Integrate jQuery with Struts2

In Struts2, the main business operations are completed through Action. In this case, jQuery is required to access Struts2's Action:
$. Post ("Action ",......)

1.1 registe. jsp page:

Function: register a user. First, enter the User Name:


Correct: the user name is not registered. You can use it;

Error: the user name has been registered;

 1.2 jQuery code:

Function checkkey () {var url = 'showallinstitute. action '; var params = {companyKey: $ (' # ckey '). attr ('value')}; jQuery. post (url, params, callbackFun);} function callbackFun (data) {response ('{warn'}.html (data); // display the returned data}



 1.3 HTML: when the text box loses focus, a callback event is triggered.

<% @ Page language = "java" import = "java. util. * "pageEncoding =" gb2312 "%> <% String path = request. getContextPath (); String basePath = request. getScheme () + ": //" + request. getServerName () + ":" + request. getServerPort () + path + "/"; %> <script language = "JavaScript" src = "js/jquery-1.6.3.js"> </script> <script type = "text/javascript" src = "js/jquery. js "> </script> <! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN"> 



Note:

1) when the text box 'key' loses focus: Call"Checkkey"Function;

2)"CheckkeyThe function determines two information:

3) asynchronous access:'Showallinstitute. action '--The Action class that determines whether the identity is correct.

4) parameters:{CompanyKey: $ ('# ckey'). attr ('value ')},A json-formatted spelling parameter.

5) Send an asynchronous request: jQuery. post (url, params, callbackFun );

 The json format is as follows:

   


1.4 Action Code:

Public String queryallinstitutes () {try {string remessage; If ("jquery ". equals (companykey) remessage = "user name has been registered"; elseremessage = "user name is not registered, you can use this user name"; httpservletresponse response = servletactioncontext. getresponse (); // response. setcontenttype ("text/html"); // response must be added to Firefox. setcharacterencoding ("UTF-8"); response. getwriter (). write (remessage);} catch (throwable e) {e. printstacktrace ();} return NULL ;}

Add the above sentence to Firefox browser; otherwise, the following error occurs:

1.5 struts. xml configuration

<Action name = "showallinstitute" class = "net. hncu. struts2.action. showallinstituteaction" method = "queryallinstitutes"> <! -- Define the relationship between processing results and view resources --> </Action>



Note:

Returned value: xmlhttprequestjquery. Post (URL,[Data],[Callback],[Type]) Overview

Load information through a remote http post request.

This is a simple POST Request function to replace complex $. Ajax. You can call the callback function when the request is successful. To execute a function when an error occurs, use $. Ajax.

Parameters URL, [data], [callback], [type]String, Map, Function, String V1.0

Url: Send request address.

Data: Key/value parameter to be sent.

Callback: Callback function when sending successfully.

Type: The returned content format is xml, html, script, json, text, and _ default.

Example

1 Description:

Request the test. php webpage and ignore the returned value:

JQuery code:
$.post("test.php");
2 Description:

Request the test. php page and send some additional data together (while still ignoring the returned value ):

JQuery code:
$.post("test.php", { name: "John", time: "2pm" } );
3 Description:

Pass the data array to the server (while still ignoring the returned value ):

JQuery code:
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
4 description:

Use ajax requests to send form data:

JQuery code:
$.post("test.php", $("#testform").serialize());
5 description:

Output results from test. php on the request page (HTML or XML, depending on the returned content ):

JQuery code:
$.post("test.php", function(data){   alert("Data Loaded: " + data); });
6 Description:

Send data to test. php and output the result (HTML or XML, depending on the returned content ):

JQuery code:
$.post("test.php", { name: "John", time: "2pm" },   function(data){     alert("Data Loaded: " + data);   });
7 description:

Obtain the content of the test. php page, store it as an XMLHttpResponse object, and process it using the JavaScript function process:

JQuery code:
$.post("test.php", { name: "John", time: "2pm" },   function(data){     process(data);   }, "xml");
8 description:

Obtain the json format returned by the test. php page ::

JQuery code:
$.post("test.php", { "func": "getNameAndTime" },   function(data){     alert(data.name); // John     console.log(data.time); //  2pm   }, "json");



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.