In JavaScript, I will give a brief description of ajax text and text, and use javascriptajax.

Source: Internet
Author: User

In JavaScript, I will give a brief description of ajax text and text, and use javascriptajax.

1. ajax entry case

1.1 build a Web environment

Ajax should be familiar to you. It is precisely because of ajax that it makes data transmission between the front-end page and the server very easy. At the same time, it can also achieve partial page refreshing. By performing a small amount of data exchange with the server in the background, AJAX can implement asynchronous updates on webpages. This means that you can update a part of a webpage without reloading the entire webpage.

For Java Web projects, ajax is mainly used for data transmission between browsers and servers.

It would be boring to pile up knowledge points alone. According to the Convention, I will not continue to introduce ajax, but write a case.

Open eclipse and create a new web project.

If you are not clear about the JavaWeb project, refer to my previous article. Me

Directory structure:

<?xml version="1.0" encoding="UTF-8"?><web-app></web-app>

This is the case. The web project has been set up.

Do not write down for the time being. Make sure that our work so far is okay.

The verification method is to create an empty jsp page under the WebContent directory and write anything in it.

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

Start tomcat and run the project.

No error is reported.

Open the browser and enter the access address. The tomcat port number here is 80, which can be left empty by default.

Http: // localhost/ajax/index. jsp

No problem.

Okay. This indicates that there is no problem in building our web project.

1.2 compile server program Servlet

Personal insights, refined sorting

The web environment has been set up. Next, let's compile a simple Servlet program. tomcat is a server. Now it has a web project named ajax, these servlets are like small functions in web projects.

Your computer contains QQ, Word, anti-virus software and other programs. A web project is an application. It is essentially the same as QQ on your computer.

You can open QQ to chat, voice, and video. These small functions, like Java Web projects, are servlets.

Many people know the framework, such as SpringMVC, which is famous for its unique controllers. In fact, these controllers are nothing to worry about. They actually encapsulate Servlet, it is essentially the same.

To write a Servlet, you must register it in web. xml. Otherwise, you will not be able to use it. You have installed a QQ, and you must register it in the registry. Isn't that the same?

Okay. I will not talk much about it. Let's write a small function, that is, a Servlet.

Inherit HttpServlet and rewrite the doGet Method

import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class MyServlet extends HttpServlet{@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System.out.println("111");}}

We will not write anything in it.

Next, register the Servlet in web. xml.

<? Xml version = "1.0" encoding = "UTF-8"?> <Web-app> <servlet> <! -- The servlet name --> <servlet-name> MyServlet </servlet-name> <servlet-class> MyServlet </servlet-class> <! -- Write the servlet class package path here --> </servlet> <servlet-mapping> <! -- Here is the address ing --> <servlet-name> MyServlet </servlet-name> <! -- Write the servlet ing address here --> <url-pattern>/MyServlet </url-pattern> </servlet-mapping> </web-app>

OK. After registering the Servlet, let's first access this function.

Restart tomcat.

Access: http: // localhost/ajax/MyServlet

1.3 front-end page design

The server applet is almost the same. Now we need to write a front-end page to interact with the server. This page is displayed to users. In other words, you can only access our Servlet through the front-end page.

Let's write a small case, send a sentence to the server on the page, and then the server will give a response.

This is a simple case, mainly used to familiarize yourself with the process.

For the sake of simplicity, I will not adjust the css style myself. use bootstrap directly.

Introduce the core css file of bootstrap.

Then, modify index. jsp

<% @ Page language = "java" contentType = "text/html; charset = UTF-8" pageEncoding = "UTF-8" %> <! DOCTYPE html PUBLIC "-// W3C // dtd html 4.01 Transitional // EN" "http://www.w3.org/TR/html4/loose.dtd"> 

Page effect:

1.4 get-based data requests

When we click the submit button, alert (). If it succeeds, it indicates that the click event is correct. Then, continue to write the code.

In the past, we submitted them through form forms, but in this case, the page will be refreshed, and the code is relatively difficult to understand.

Since ajax came out, this situation has been greatly improved, and the partial refresh technology was quite good at the time.

I will first give the implementation code:

btn.onclick = function(){var xhr = window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");xhr.open("get","MyServlet?message="+document.getElementsByTagName("input")[0].value,true);xhr.send();xhr.onreadystatechange = function(){if(xhr.readyState==4 && xhr.status==200){alert(xhr.responseText);}};}

Modify MyServlet at the same time

@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {String msg = req.getParameter("message");System.out.println(msg);}

Restart tomcat to access the index. jsp page.

Currently, browsers generally have debugging functions. Click F12 to debug the interface. Then, find a network. Google Chrome is used as an example.

The network view displays all the data interactions, including the introduced js, css files, and various requests and responses.

For example, I will refresh the page now.

When I refresh the page, the server first receives a URL: http: // localhost/ajax/index. jsp.

This is a request. After receiving this request, the server returns the index.jsppage and bootstrap.min.css file to me.

Because I actually imported bootstrap.min.css in index.jsp, he loaded it together.

Now, I enter a sentence and click Submit to see what will happen?

We submit the content in the input box to the server program MyServlet.

The console has already accepted this. We are lucky to have no problem with Chinese garbled characters, so we should ignore the garbled characters first.

Alert is empty because nothing is returned in MyServlet.

Okay, let's return a sentence to the browser.

@ Overrideprotected void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {String msg = req. getParameter ("message"); System. out. println (msg); resp. setContentType ("text/html; charset = UTF-8"); PrintWriter out = resp. getWriter (); out. println ("Hello, this is the message returned by the server! "); Out. flush (); out. close ();}

Click Submit again

OK.

Next, let's take a look at the specific request information.

After comparing the js code, you can see it at a glance.

btn.onclick = function(){var xhr = window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");xhr.open("get","MyServlet?message="+document.getElementsByTagName("input")[0].value,true);xhr.send();xhr.onreadystatechange = function(){if(xhr.readyState==4 && xhr.status==200){alert(xhr.responseText);}};}

ReadyState:

0: the request is not initialized.

1: The server connection has been established and has not been sent

2: The request has been received

3: The request is being processed

4: The request is complete and the response is ready.

When readyState is 4 and the status is 200, the response is ready.

The request method is get, and the responseText will be printed only when the returned status code is 200. This is the corresponding

Out. println ("Hello, this is the information returned by the server! ");

This sentence.

1.5 post-based data requests

The get method will display the value you submitted in the URL address bar. The post method will not. Therefore, the post method is relatively safe.

The post method is similar to the get method in the process, so I will directly go to the Code:

Window. onload = function () {var btn = document. getElementById ("submit"); btn. onclick = function () {var xhr = window. XMLHttpRequest? New XMLHttpRequest (): new ActiveXObject ("Microsoft. XMLHTTP "); xhr. open ("post", "MyServlet", true); xhr. setRequestHeader ("Content-type", "application/x-www-form-urlencoded"); var postData = {message: document. getElementsByTagName ("input") [0]. value}; var postDataStr = (function (obj) {// convert it to the string required by post. var str = ""; for (var prop in obj) {str + = prop + "=" + obj [prop] + "&"} return str ;}) (postData); alert (postDataStr); xhr. send (postDataStr); xhr. onreadystatechange = function () {if (xhr. readyState = 4 & xhr. status = 200) {alert (xhr. responseText );}};}};

MyServlet. java

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 MyServlet extends HttpServlet {@ Overrideprotected void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {req. setCharacterEnc Oding ("UTF-8"); String msg = req. getParameter ("message"); System. out. println (msg); resp. setContentType ("text/html; charset = UTF-8"); PrintWriter out = resp. getWriter (); out. println ("Hello, this is the message returned by the server! "); Out. flush (); out. close () ;}@ Overrideprotected void doPost (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet (req, resp );}}

The above is a simple example of JavaScript that I will introduce to you. I hope it will be helpful to you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!

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.