accp8.0 Conversion Textbook chapter 10th Ajax and jquery comprehension and practice

Source: Internet
Author: User

c/S (CLIENT/SERVER) structure, known as the client and server structure.
The b/S (BROWSER/SERVER) structure is the browser and server structure.

Recognize Ajax, XMLHttpRequest, use jquery to implement AJAX, handle JSON-formatted response data, and implement Ajax with native JavaScript

I. Miscellaneous notes

1. Traditional Web technologies and AJAX requests in different ways Ajax is only getting the elements needed to traditional refresh all

The full name of 2.ajax is "asynchronous JavaScript and XML" (Asynchronous JavaScript and XML)

3.ajax Workflow UI sends HTTP requests via JavaScript to AJAX---server (processing requests)

Then return the xml/json/html data to the Ajax engine and return the DOM+CSS to the user interface

4.XMLHttpRequest provides the ability to send requests asynchronously

Common methods

Open (String method,string url,boolean async) Creates a new HTTP request,

Send the request to the server-side,

setRequestHeader (String header,string value) sets the requested HTTP header information,

5. The old version of IE browser and the new edition of the majority of browsers created XMLHttpRequest not the same

6. Event onReadyStateChange: callback function

Two. On-machine section

1. Implement check whether the registered user's mailbox is present (Ajax using the original eco-JavaScript)

<div style= "left:2200px;" >
<form action= "" method= "get" >
Registered Email: <input type= "text" id= "email" onblur= "checkemail ()" ><label id= "Samp" >*</label><br/> <br/>
&nbsp; User name: <input type= "Text" >*<br/><br/>
&nbsp;&nbsp; Password: <input type= "Password" >*<br/><br/>
Confirm Password: <input type= "Password" >*<br/><br/>
<div style= "margin-left:100px;" ><input type= "Submit" value= "Registration" ></div>

</form>
<script type= "Text/javascript" language= "JavaScript" >
function Checkemail () {
Alert ("HNJKL");
Create a XMLHttpRequest Object
if (window. XMLHttpRequest) {//return True when the description is new version IE browser or other browser
Xmlhttprequest=new XMLHttpRequest ();
}else{//returns False when the description is old version IE browser
Xmlhttprequest=new XMLHttpRequest ("Microsoft.XMLHTTP");
}
Setting the callback function
Xmlhttprequest.onreadystatechange=callback;
Gets the value of the User Name text box
var email=$ ("#email"). Val ();
Initializing the XMLHttpRequest component
var url= "userservlet?email=" +email;//server-side URL address, name is the value of the User Name text box
Xmlhttprequest.open ("GET", url,true);
Send Request
Xmlhttprequest.send (NULL);
Key code for handling server responses in callback function callback ()
function CallBack () {
if (xmlhttprequest.readystate==4&&xmlhttprequest.status==200) {
var Date=xmlhttprequest.responsetext;
if (date== "true") {
$ ("#samp"). HTML ("Mailbox is occupied");//samp is the ID of the SAMP that displays the message
}else{
$ ("#samp"). HTML ("Mailbox can be registered");
}
}
}
}

</script>
</div>

The code in the servlet is as follows

Package web;

Import java.io.IOException;
Import Java.io.PrintWriter;

Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;

public class Userservlet extends httpservlet{

@Override
protected void doget (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {
TODO auto-generated Method Stub

Request.setcharacterencoding ("UTF-8");
Boolean emailcheck=false;
String email=request.getparameter ("email");
if ("[email protected]". Equals (email)) {
Emailcheck=true;

}
else {
Emailcheck=false;
}
Response.setcontenttype ("Text/html;charset=utf-8");
PrintWriter Out=response.getwriter ();
Out.print (Emailcheck);
Out.flush ();
Out.close ();

}

@Override
protected void DoPost (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {
TODO auto-generated Method Stub
Request.setcharacterencoding ("UTF-8");
This.doget (request, response);
}
}

2. Use the $.ajax () method to asynchronously check whether the registered mailbox already exists

<div style= "left:2200px;" >
<form action= "" method= "get" >
Registered Email: <input type= "text" id= "email" onblur= "checkemail ()" ><label id= "Samp" >*</label><br/> <br/>
&nbsp; User name: <input type= "Text" >*<br/><br/>
&nbsp;&nbsp; Password: <input type= "Password" >*<br/><br/>
Confirm Password: <input type= "Password" >*<br/><br/>
<div style= "margin-left:100px;" ><input type= "Submit" value= "Registration" ></div>

</form>
<script type= "Text/javascript" language= "JavaScript" >
function Checkemail () {
var email=$ ("#email"). Val ();
$.ajax ({
"url": "Userservlet",
"Type": "Get",
"Data": "Email=" +email,
"DataType": "Text",
"Success": CallBack,
"Error": function () {
Alert ("error occurred");
}
});
function CallBack (data) {
if (data== "true") {
$ ("#samp"). HTML ("Mailbox is occupied");//samp is the ID of the SAMP that displays the message
}else{
$ ("#samp"). HTML ("Mailbox can be registered");
}
}

}
</script>
</div>

3. Display JSON data with common page elements

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%>
<%
String path = Request.getcontextpath ();
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";
%>

<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
<base href= "<%=basePath%>" >

<title>my JSP ' workthree.jsp ' starting page</title>

<meta http-equiv= "Pragma" content= "No-cache" >
<meta http-equiv= "Cache-control" content= "No-cache" >
<meta http-equiv= "Expires" content= "0" >
<meta http-equiv= "keywords" content= "keyword1,keyword2,keyword3" >
<meta http-equiv= "description" content= "This is my page" >
<!--
<link rel= "stylesheet" type= "Text/css" href= "Styles.css" >
-
<script type= "Text/javascript" src= "Js/jquery-1.8.3.js" ></script>
<script type= "Text/javascript" >
$ (document). Ready (function () {
var personary=["Da Dong-13838381438 cities in Zhoukou, Henan province-", "Xiao Shun-xx city, Guangdong Province"];
var person=[{"id": "1001", "Name": "Da Dong", "Address": "Henan Province Zhoukou", "Phone": "13838381438"},
{"id": "1002", "Name": "Xiao Chun", "Address": "XX City of Hunan province", "Phone": "13838381438"},
{"id": "1003", "name": "Xiao Shun", "Address": "XX City of Guangdong province", "Phone": "13838381438"},
{"id": "1004", "Name": "Xiao Mo", "Address": "XX City of Hebei province", "Phone": "13838381438"}];
var $divv =$ ("#con");
var $table =$ ("<table border= ' 1 ' ></table>"). Append ("<tr><td>ID</td><td> name < /td><td> address </td><td> Mobile </td></tr> ");
$DIVV. Append ($table);
$ (person). each (function () {
$table. Append ("<tr><td>" +this.id+ "</td><td>"
+this.name+ "</td><td>"
+this.address+ "</td><td>"
+this.phone+ "</td></tr>");
});


2. Drop-down box
var $ary =$ (personary);
var $ul =$ ("#arul");
var $sel =$ ("#arse");
$ary. Each (function (i) {
$sel. Append ("<option value=" + (i+1) + ">" +this+ "</option>");
});
});
</script>


<body>

<div id= "Con" >

</div>
<div id= "Conn" >
<select id= "arse" ></select>
</div>
</body>

4. Using JSON to generate Administrator news management pages in Ajax

The page will not be uploaded here if necessary complete project code in CSDN can find Sogou search (accp8.0 conversion textbook chapter X) can download

The main thing is JS

/**
* Created by Administrator on 2017/7/4.
*/
$ (function () {
$.ajax ({
"url": "UserServlet2",
"Type": "POST",
"Data": "Por=user",
"DataType": "JSON",
"Success": CallBack
});
$ ("#news"). Click (function () {
Initnews ();
});
$ ("#topics"). Click (function () {
Inittopics ();
});
});

function CallBack (data) {
var $data =$ (data);
var $userul =$ ("#userul");
$data. each (function () {
$userul. Append ("<li>" +this.naem+ "&nbsp;&nbsp;" +this.pwd+ "&nbsp;&nbsp;<a href=" > Modify </a>&nbsp;&nbsp;<a href= "> Delete </a> </li> ");
});
}
function Initnews () {
$.ajax ({
"url": "UserServlet2",
"Type": "POST",
"Data": "Por=news",
"DataType": "JSON",
"Success": Callnews
});

function Callnews (News) {
Alert ("ddd");
var $userul =$ ("#userul"). empty ();
for (Var i=0;i<news.length;) {
$userul. Append (
"<li>" +news[i].title+ "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; " +news[i].author+ "&nbsp;&nbsp;<a href=" > Modify </a>&nbsp;&nbsp;<a href= "> Delete </a ></li> "
);
i++;
if (i==news.length) {

Break
}
}

}
}
function Inittopics () {
$.ajax ({
"url": "UserServlet2",
"Type": "POST",
"Data": "Por=top",
"DataType": "JSON",
"Success": Calltopics
});

function Calltopics (top) {

var $userul =$ ("#userul"). empty ();
for (Var i=0;i<top.length;) {
Alert ("ddd");
$userul. Append (
"<li>" +top[i].topics+ "&nbsp;&nbsp;<a href=" > Modify </a>&nbsp;&nbsp;<a href= " > Delete </a></li> "
);
i++;
if (i==top.length) {

Break
}
}
}
}

Servlet code

Package web;

Import java.io.IOException;
Import Java.io.PrintWriter;
Import java.util.List;

Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;


Import dao.newlist;
Import Dao.topdao;
Import Daoimpl.newlistimpl;
Import Daoimpl.topimpl;
Import Entity.news;
Import Entity.top;


public class UserServlet2 extends httpservlet{

@Override
protected void doget (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {
TODO auto-generated Method Stub

DoPost (request, response);

}

@Override
protected void DoPost (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {
TODO auto-generated Method Stub


Request.setcharacterencoding ("UTF-8");
String por=request.getparameter ("Por");
if (Por.equals ("News")) {
NewList nd=new Newlistimpl ();
List<news> listnews=nd.allnewslist ();
StringBuffer newssub=new StringBuffer ("[");
for (int i=0;;) {
News N=listnews.get (i);
Newssub.append ("{\" title\ ": \" "+n.getntitle () +" \ ", \" author\ ": \" "+n.getauthour () +" \ "}");
i++;
if (I==listnews.size ()) {
Break
}else{
Newssub.append (",");
}
}
Newssub.append ("]");
Response.setcontenttype ("Text/html;charset=utf-8");
PrintWriter Out=response.getwriter ();
Out.print (newssub);
Out.flush ();
Out.close ();

}
else if (por.equals ("top")) {
Topdao nd=new Topimpl ();
List<top> Listtop=nd.alltop ();
StringBuffer topsub=new StringBuffer ("[");
for (int i=0;;) {
Top Top=listtop.get (i);
Topsub.append ("{\" topics\ ": \" "+top.gettcontent () +" \ "}");
i++;
if (I==listtop.size ()) {
Break
}else{
Topsub.append (",");
}
}
Topsub.append ("]");
Response.setcontenttype ("Text/html;charset=utf-8");
PrintWriter Out=response.getwriter ();
Out.print (topsub);
Out.flush ();
Out.close ();
}
}
}

5. Using JSON to generate theme management pages in Ajax

In the four in the machine

Five. Summary section

1. Traditional Web development technology sends requests through a browser and Ajax is sent via JavaScript's XMLHttpRequest object

The traditional response is a full page and JavaScript returns the required data

Key elements of 2.Ajax

→javascript language: The main development language of Ajax technology

→xml/json/html: Used to encapsulate data

→dom (Document Object Model): modifying page elements

→CSS: Changing Style

→ajax Engine: XMLHttpRequest Object

3. How to create a XMLHttpRequest object (two new and old)

Welcome to ask questions, welcome to the wrong, welcome to discuss the learning information in need of private chat post comments can be answered

The original in the blog Park http://www.cnblogs.com/a782126844/have the need to contact buckle: 2265682997

accp8.0 Conversion Textbook chapter 10th Ajax and jquery comprehension and practice

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.