Ajax Study Notes 01
Course:
Deploy the first Ajax Program |
Learning steps:
1. Create a Java Web project -- ajax_01:
2. Create servlet, package name test, class name ajaxservlet, dopost () code:
- Request. setcharacterencoding ("UTF-8 ");
- Response. setcontenttype ("text/html; charset = UTF-8 ");
- Printwriter out = response. getwriter ();
- String S = request. getparameter ("username ");
- Out. Print ("returned result:" + S );
|
3. Modify the index. jsp page code:
- <Div id = "result"> </div>
- <Form ID = "form1" Action = "Servlet/ajaxservlet" method = "Post">
- <Input type = "text" id = "username" name = "username"/>
- <Input type = "button" id = "Submit" value = "Submit"
- Onclick = "verify ()"/>
- </Form>
|
4. Create the jslib package under webroot, put jquery. js in this package, create the verify. js file, and write the code:
- Function verify (){
- // 1. Obtain the content in the text box
- VaR jqueryobj = $ ("# username ");
- VaR username = jqueryobj. Val ();
- Alert (username );
- // 2. Send the data in the text box to the Servlet
- // Suspect that when the following code sends data to the servlet, garbled characters will be transmitted in Chinese.
- // If you press enter directly in the editing box, the servlet will be loaded directly, and the JS page will be loaded first after you click the button,
- // Then pass the obtained data to the servlet through this JS page
- $. Get ("Servlet/ajaxservlet? Username = "+ username, null, callback/* callback function */);
- }
- Function callback (data ){
- Alert ("the server data is back ");
- // 3. Accept the data returned by the server
- VaR resultobj = $ ("# result ");
- // 4. dynamically display the data returned by the server to the page
- Resultobj.html (data );
- }
|
5. Import JS Code in index. jsp:
- <SCRIPT type = "text/JavaScript" src = "jslib/verify. js"> </SCRIPT>
- <SCRIPT type = "text/JavaScript" src = "jslib/jquery. js"> </SCRIPT>
|