struts2-Simple Ajax Application __ajax

Source: Internet
Author: User

Scenario: When the user registers, enter the user name in the text input box, and after the user has entered, determine if the user name exists in the database. In this scenario, the server simply returns TRUE or FALSE.

Write in Java action:

 * * for Ajax
/private InputStream InputStream;
Public InputStream getInputStream () {return
    inputstream;
}

private String name;
public void SetName (String name) {
    this.name = name;
}
Public String Validatename () throws Unsupportedencodingexception {
    Boolean f = employeeservice.isnamevalidate ( name);
    System.out.println (f);
    InputStream = new Bytearrayinputstream (f?) 1 ":" 0 "). GetBytes (" UTF-8 "));
    return "ajax-success";
}

Configuration in Struts2.xml file:

<result type= "Stream" Name= "ajax-success" >
    <param name= "ContentType" >text/html</param>
    <param name= "InputName" >inputStream</param>
</result>

Front:

//send ajax request var url = "Emp-validatename.action"; var args = {"Name": Val, "Time": New Date ()}; $.po
    St (URL, args, function (data) {if (data== "1") {$this. After ("<font color= ' green ' > name available </font>");
    }else if (data= "0") {$this. After ("<font color= ' Red ' > name not Available </font>");
    }else{alert ("Server Exception"); }
});

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.