Java Xiaobai Learning Guide [day40] ---JavascriptDOM&Ajax request

One, DOM

DOM [Document Object Model] Chinese name: Document Object Model.

1. DOM overview

There are three elements under the document object: label elements, attribute elements, and text elements

Insert picture description here

The contents of the following three element operations are the following

<body>
	<div id="mydiv">这是我的div</div>
	<div>
		<input type="text" name="username" />
		<input type="checkbox" name="hobboy" value="java" />java 
		<input type="checkbox" name="hobboy" value="C" />C 
		<span>那些年错过的大雨</span>
	</div>
</body>

2. Label element operation

  • document.getElementById()——Get the tag object through the ID of the tag element [id is unique]
  • document.getElementsByName()——Get the label object through the name attribute of the label element, and return an array
  • document.getElementsByTagName()——Get the tag object by tag name and return an array
  • document.createElement()-create a new element
  • appendChild()-parent node append child node
  • removeChild()-the parent node deletes the child node
<script type="text/javascript">
	/* 要注意代码的加载顺序,要么放在需要操作的代码后面,要么加上weindow.onload文档加载事件,文档加载完毕之后,才执行内部的程序 */
	window.onload = function(){
     
     
		//通过标签元素的ID获取到标签对象[id具有唯一性]
		var div1 = document.getElementById("mydiv");
		console.debug(div1);
		//通过标签元素的name属性获取到标签对象,返回的是数组
		var div2 = document.getElementsByName("hobboy");
		console.debug(div2);
		//通过标签名称获取到标签对象,返回的是数组
		var div3 = document.getElementsByTagName("input");
		console.debug(div3);
		
		//添加标签元素
		var input = document.createElement("input");
		input.type = "text";//增加属性
		console.debug(input);
		//父节点追加子节点
		div1.appendChild(input);
		console.debug(div1);
		//删除
		div1.removeChild(input);
	}
</script>

3. Attribute element operation

  • setAttribute("type","button")-set attribute

  • getAttribute("type")-Get the attribute value

  • removeAttribute()-delete an attribute;

  • node.style. style-set the style

  • node.className-set the style name

<style type="text/css">
	.div{
     
     
		background-color: purple;
	}
</style>
<script type="text/javascript">
	/* 要注意代码的加载顺序,要么放在需要操作的代码后面,要么加上weindow.onload文档加载事件,文档加载完毕之后,才执行内部的程序 */
	window.onload = function(){
     
     
		//1、查找属性元素
		var div1 = document.getElementById("mydiv");
		var id = div1.getAttribute("id")
		console.debug(id);
		//2、设置属性,修改属性
		div1.setAttribute("name","divid");
		console.debug(div1);
		//3、删除某属性;
		div1.removeAttribute("name");
		//4、 设置样式两种方式
		//方式一,常用设置样式名
		div1.className = "div"//类似于直接添加了一个属性class,通过css再calss加载设置样式
		//方式二,设置样式
		div1.style.backgroundColor="pink"
	}
</script>

4. Operation of text elements

  • innerHTML (CRUD)-set or get elements with tags
  • innerText (CRUD)-set or get the plain text in the element
<script type="text/javascript">
	/* 要注意代码的加载顺序,要么放在需要操作的代码后面,要么加上weindow.onload文档加载事件,文档加载完毕之后,才执行内部的程序 */
	window.onload = function(){
     
     
		var div1 = document.getElementById("mydiv");
		var div2 = document.getElementById("youdiv");
		//查找文本
		var text = div1.innerText;
		console.debug(text);//这是我的div
		var html = div2.innerHTML;
		console.debug(html);//获得所有代码
		//增加、修改、删除
		div1.innerText = "这是innerText";
		console.debug(text);//这是innerText
		div2.innerHTML = "这是innerHTML";
		console.debug(html);
		//区别,innerText只能操作纯文本,innerHTML可以操作元素
		div1.innerText = "<input type='checkbox' name='hi' value='java'/>java";
		div2.innerHTML = "<input type='checkbox' name='hi' value='java'/>java";
	}
</script>

5. The way of event registration

  • The onabort user terminates the page loading.

  • onblur The user leaves the object. lose focus

  • onchange The user changes the value of the object.

  • onclick The user clicks on the object.

  • ondblclick The user double-clicks the object.

  • onfocus (the opposite of onblur) The user activates the object.

  • onkeydown Press the keyboard.

  • onkeypress Press the keyboard.

  • onkeyup Release the keyboard.

  • The onload page finishes loading. Note: In Netscape, this event occurs when the page loads.

  • onmousedown The user presses the mouse button.

  • onmousemove The mouse pointer moves on the object.

  • onmouseover Move the mouse pointer to the object.

  • onmouseout Move the mouse pointer out of the object.

  • onmouseup The user releases the mouse button.

  • onreset The user resets the form.

  • onselect The user selects content on the page.

  • onsubmit The user submits the form.

  • onunload The user closes the page.

<style type="text/css">
	.div{
     
     
		width:200px;
		height:200px;
		background-color: purple;
	}
</style>
<script type="text/javascript">
	/* 事件注册公用两种,
	(1)元素上直接注册
	(2)元素.事件名称 (常用)
	*/
	//第一种:缺点是js代码与html代码写在一起了
	function dian(){
     
     
		var div1 = document.getElementById("mydiv");
		div1.className="div";
	}
	//第二种:
	window.onload = function(){
     
     //文档加载事件
		var div2 = document.getElementById("youdiv");
		div2.onclick=function(){
     
     //元素.事件名称
			this.className="div";//谁调用函数,this就指代谁
		}
		//案例:显示密码于隐藏密码之间的切换
		var div3 = document.getElementById("but");
		div3.onclick=function(){
     
     
			var pwd = document.getElementById("pwd");
			if(pwd.type == "password"){
     
     
				pwd.type = "text";
			}else{
     
     
				pwd.type = "password";
			}
		}
	}
</script>
</head>
<body>
<div id="mydiv" onclick="dian()">这是我的div</div>
<div id="youdiv">你的div</div>
<input id="pwd" type="password" /><input id="but" type="button" value="切换" />
</body>

Two, Ajax asynchronous request

1. Ajax overview

AJAX stands for Asynchronous Javascript And XML (asynchronous JavaScript and XML), which is a web development technology to improve user experience

Traditional interaction method: The client (browser) sends a request to the server. After the server receives the request and processes it, it will reload a complete web page (and this web page is almost the same as the previous one), and return the response data to the client ( Browser), the browser parses the webpage and displays it to the user

Insert picture description here

Ajax interaction mode: asynchronous request, the colleague who sends the request can continue to operate the page. The page is not destroyed; part of the data is returned, unnecessary data transmission is reduced, and network resources are introduced. The page is not refreshed, but part of the page data is updated;

Insert picture description here

Summary: The reason for the emergence of Ajax: better improve the user experience, and improve the efficiency of the server, and reduce the transmission of unnecessary data in the network

Writing ajax code is writing js code. Learning ajax is actually learning to use the ajax (XMLHttpRequest object) object of the browser to send asynchronous requests and update the response data to the page.

2. Get the Ajax object

Two creation methods: 1. Judgment method; 2. try...catch... method

<script type="text/javascript">
	/* 判断方式 */
	var xhr;
	if(window.XMLHttpRequest){
     
     //IE以外的浏览器  没有undefined false
		xhr = new XMLHttpRequest();
	}else{
     
     //IE浏览器
		xhr = new ActiveXObject();
	}
	console.debug(xhr)
	/* try...catch...方式 */
	var ajax;
	try {
     
     
		//如果是其它浏览器,这句代码可以成功,ajax对象就拿到了
		ajax = new XMLHttpRequest();
	} catch (e) {
     
     
		//如果是IE,上面肯定会报错,被抓取,就执行下面这句代码(IE支持)
		ajax = new ActiveXObject();
	}
	console.debug(ajax)
</script>

3 、 Ajax 的 API

https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/open

Insert picture description here

4. Ajax sends get request (get server time)

SpringMVC environment is set up

(1) jar

(2) resource

(3) web.xml configuration

(4) Configure the operating environment

<%@ 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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
	<script type="text/javascript">
	//1、获取Ajax对象
	function createXhr(){
		var xhr;
		if(window.XMLHttpRequest){//有这个方法,则是其他浏览器
			xhr = new XMLHttpRequest();
		}else{//没有该方法则为undefined,则为ie浏览器
			xhr = new ActiveXObject();
		}
		return xhr;
	}
	//2、发送请求,获取服务器时间
	function getTime(){
		//获取ajax对象
		var xhr = createXhr();
		//创建请求
		xhr.open("get","/getTimer");
		//第一个参数:使用GET提交还是POST提交,第二个参数:请求的url地址,第三个参数(默认是true):请求是同步还是异步
		//创建监听,对返回的状态做反馈
		xhr.onreadystatechange = function(){
			if(xhr.readyState == 4 && xhr.status == 200){
				//服务器返回一个文本
				var text = xhr.responseText;
				var span = document.getElementById("span");
				span.innerText = text;
			}
		}
		//发送请求
		xhr.send();
	}
	//做一个时间设定任务
	function start(){
		setInterval("getTime()", 2000);
	}
	</script>
</head>
<body>
	服务器时间:<span id="span"></span><input type="button" οnclick="start()" value="获取时间">
</body>
</html>

Set up the controller file

@Controller
public class TimeController {
    
    
	@RequestMapping("/getTimer")
	//记得响应注入
	@ResponseBody
	public String getTimer(){
    
    
		return new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date());
	}
}

5. Ajax sends Post request (login interface)

SpringMVC environment is set up

(1) jar

(2) resource

(3) web.xml

(4) Configure the operating environment

<%@ 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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
	<script type="text/javascript">
	//先要获取ajax对象,同时判断IE和其他浏览器
	function createXhr(){
		var xhr;
		if(window.XMLHttpRequest){//有这个方法,则是其他浏览器
			xhr = new XMLHttpRequest();
		}else{//没有该方法则为undefined,则为ie浏览器
			xhr = new ActiveXObject();
		}
		return xhr;
	}
	//发送请求,获取服务器时间
	function login(){
		//获取ajax对象
		var xhr = createXhr();
		//创建请求
		xhr.open("post","/login");
		xhr.onreadystatechange = function(){//创建监听函数,对任何状态都进行监听
			if(xhr.readyState==4 && xhr.status==200){
				var text = xhr.responseText;//服务器返回文本
				if(text == "true"){
					alert("登陆成功");
				}else{
					alert("铁憨憨,账号、密码都记不住嘛");
				}
			}
		}
		//使用ajax的post提交,你要让后台传递参数,你还得设置请求头信息
		xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");//传递的参数是以普通文本传输的
		//设置参数
		var username = document.getElementById("uname").value;
		var password = document.getElementById("upwd").value;
		var param = "username="+username+"&password="+password;
		xhr.send(param);//发送请求
	}
	</script>
</head>
<body>
	用户名:<input type="text" id="uname" name="username" /><br/>
	密&emsp;码:<input type="password" id="upwd" name="password" /><br/>
	<input type="button" value="登录" οnclick="login()" />
</body>
</html>

Set up the controller file

@RequestMapping("/login")
	//记得响应注入
	@ResponseBody
	public boolean login(String username,String password){
    
    //注意这的形参名要与前台传过来的一致
		//模拟数据库获取的数据
		String na = "wang";
		String pa = "12138";
		System.out.println(username+"--------"+password);
		//判断的时候可以用数据库的数据调用方法,避免遇到参数为null
		if (na.equals(username) && pa.equals(password)) {
    
    
			return true;
		}else{
    
    
			return false;
		}
	}

6. Ajax request encoding problem

1. Solve the garbled problem in GET request

Tomcat 8.0 has solved this problem

2. Garbled code in POST request

Set the filter in web.xml

<!-- SpringMVC写好的过滤器 -->
	<filter>
		<!-- 这个名字可以换,只要与下面的对应 -->
		<filter-name>characterEncoding</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<!-- 不能变的名字 -->
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>characterEncoding</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

7. Ajax request IE cache problem

The AJAX object provided by IE browser will first check whether the address has been visited when sending a GET request. If the address has already been visited, then the browser will not send the request

Solution:

  • (1) Send post request

  • (2) To trick the browser into thinking that we are sending a different request:

    xhr.open('get','random?r=' + Math.random()); //Pass random number

    xhr.open('get','random?' + (new Date()).getTime()); //Pass the timestamp
    ncoding
    UTF-8



    characterEncoding
    /*




## 7、Ajax请求IE缓存问题

IE浏览器提供的AJAX对象,在发送GET请求时,会先查看是否访问过该地址,如果该地址已经访问过,那么浏览器不再发送请求

解决方式:

- (1) 发送post请求

- (2) 欺骗浏览器,请它以为我们正在发送不同的请求:

  xhr.open('get','random?r=' + Math.random());		//通过随机数

  xhr.open('get','random?' + (new Date()).getTime());	//通过时间戳

Guess you like

Origin blog.csdn.net/WLK0423/article/details/111245432