Beginners Ajax Asynchronous commit get JSON type data

Source: Internet
Author: User
Tags gettext
When you encounter the need to verify the existence of existing records in the database, you need to first use Ajax to submit the background action to determine whether there are records in the database, by returning JSON data, reception in the foreground, output results: For example, take the login user example: <% String path =
Request.getcontextpath ();
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/"; %> first define the login button in the Global Path form form type= "button" to submit manually, plus the onclick event onclick= "Login.submit ();" You can write an error block near the user name box, Define a message property to pass error messages: <div id= "errmsg" class= "Errorbox" style= ' Display:none; ' > <span id= "err_id" ></span><s:property value= "getText (message)" Escape= "false"/> </div> (
The form is not required to write action and onsubmit () associated login and login_func var login = new Login_func (); In the JS definition Loginfunc this method var login_func=function () {} login_func.prototype.submit=function () {Here can add the user name password is null checksum as Var us
	Ernamevar = document.getElementById (' username '). Value or =$ (' #username '). Val ();
		You can refer to: if ($ (' #username '). val () = = ') {$ (' #errmsg '). CSS ({' Display ': '});
		$ (' #err_id '). html (' <s:property value= "getText (' login.userName.null ') '/> '); return FALSe
		else if ($ (' #password '). val () = = ') {$ (' #errmsg '). CSS ({' Display ': '});
		$ (' #err_id '). html (' <s:property value= "getText (' login.passWord.null ') '/> ');
	return false;
	If the json out parameter has two keys, then set two variables to pick up the two keys, a success, a failure var submitflag = null;	
	var errorflag = null; The user name and password of the interface need to be encapsulated into a JSON parameter, and the Post method is used to pass the value var userparam = {"User.username": $ ("#username"). Val (), "User.password": $ ("#pas
	Sword "). Val ()}, where user.username indicates that the background can get its value by User.getusername (), and if the parameter is username, the background user is null ....
	If you want to alert Userparam data method, you can see an article. Define Ajax $.ajax ({url: ' validate.shtml ',//GO first check action Cache:false,//Deny cache async:false,//asynchronously Commit type: ' Post ', Data:userparam, DataType: ' JSON ', success:function (data) {Submitflag = data. submit_flag;//if this way to get backstage Submit_flag, Google browser no problem, Firefox no problem, IE6 is a problem, he does not recognize submit_flag is what errormessage = data.
					Error_message; So use the following method to get the JSON data//retdata storage value//pro Storage key var retdata = eval ("+data+")");
								For (Var pro in Retdata) {if (pro== "Submit_flag") {alert (Retdata[pro));
									else if (pro== "Failure_flag") {alert (Retdata[pro));
								Return
							}/* IF (retdata[pro]== "Submit_flag") {alert ("Save success!");
							else if (retdata[pro]== "Failure_flag") {alert ("role name already exists!");
						}*/}//or in this way show more friendly if (pro== "Submit_flag") {commit operation, see below} else if (failed key) {
						$ (' #errmsg '). CSS ({' Display ': '});
						
							$ ("#err_id"). HTML ("");
								If (pro== failed key) {$ ("#err_id"). Append ("User does not exist");
								else if (pro== failed key) {$ ("#err_id"). Append ("Password error");
		}
					}
			    }
			 }
		); if (' Undefined '!= submitflag && null!= submitflag && ' true ' = = Submitflag) {DOCUMENT.GETELEMENTB Yid ("LoginForm"). action= ' <%=basePath%> ' + "login.shtml";//success is submitted login DOCUMENT.GEtelementbyid ("LoginForm"). Submit ();
			} else {}} background: HttpServletResponse response = Servletactioncontext.getresponse ();
			Response.setcontenttype ("Text/html;charset=utf-8");
			Response.setheader ("Pragma", "No-cache");
			Response.setheader ("Cache-control", "No-cache");
			Response.setheader ("Cache-control", "No-store");
			PrintWriter writer = Response.getwriter ();
			Jsonobject json = new Jsonobject ();
			Verification Operation Successful Json.put ("Submit_flag", "Save success!");
			Failure Json.put ("Failure_flag", "Username already exists!");
    			Writer.write (Json.tostring ());
    			Writer.flush ();
Writer.close ();




 Return JSON type in struts2: <result type= "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.