01 Ajax knowledge

Ajax

First, synchronous and asynchronous

  1. Synchronization (Synchoronous): When a task is running, you can not perform other tasks
  2. Asynchronous (Asynchoronous): When a task is turned on, you can open other tasks
Synchronization scenarios Asynchronous scenarios
Website Access User name verification
a tag jump chatroom
Submit form submission Baidu search term suggestions

Two, Json data format

2.1 JS object data format

var stu = {
    name:'Julay',
    age:20,
    sex:'nv'
}

2.2 Json data format

Json (JavaScript Object Notation) is a data format JS representation of the object out of a string

  1. Json use {}represents an object
  2. Json need to use the property name " "in quotes
  3. Represents the whole string, the outermost layer is required' '
//Json字符串
var jsonStr = '{"name":"Tom","age":18}';
//Json数组
var JsonArr = '[
	{"name":"julay","age":18},
	{"name":"Tom","age":20}
]';

Application of Ajax Json in:

The database server queries the result returned is JS object array, a string is automatically converted into a response transmitted to the Json Ajax.

2.3 Processing of response data Json

  • Json string into a JS object array:var json_js = JSON.parse();
  • JS array is converted into Json:JSON.stringify(js_arr);
  • JS objects are converted into Json:var json_str = JSON.stringify(js_obj);

JS converted into an array of objects may be used JavaScript methods and properties of the subject process

  • JSON_Ajax.js
//1.创建异步对象
var xhr = new XMLHttpRequest();
//2.绑定监听事件
xhr.onreadystatechange = function(){
    if(xhr.readyState ==4 && xhr.status == 200){
        //result保存的是json字符串
        var result = xhr.responseText;
        //转换js对象数组
        var jschange = JSON.parse();
        alert(jschange);
    }
}
//3.打开链接
var url = "/test/getajax?uname="+uname.value+"&upwd="+upwd.value;//拼接URL字符串
xhr.oprn("get",url,true);
//4.发送请求
xhr.send();

Three, XML Extensible Markup Language

XML (eXtensible Markup Language) tag is not predefined, and needed to customize the user, and its purpose is to transfer data.

3.1 XML syntax

  1. XML document declaration:<?xml version="1.0" encoding="UTF-8"?>
  2. All labels must appear in pairs , no single label
  3. Strictly case-sensitive
  4. Tag allows nested
  5. Each tag allows custom attributes, attribute values " "comprising
  6. Each XML document has one and only one root element
  • book.xml
<?xml version="1.0"? encoding="utf-8">
<books>
<booklist>
	<name>《时间简史》</name>
	<author>霍金</author>
</booklist>
<booklist>
	<name>《三国演义》</name>
	<author>罗贯中</author>
</booklist>
<booklist>
	<name>《红楼梦》</name>
	<author>曹雪芹</author>
</booklist>
</books>
  • XML_Ajax.js
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
    if(xhr.readyState == 4&&xhr.state == 200){
        //books相当于XML里根目录的books标签,以下同理
        var books = xhr.responseXML;
        //得到booklist标签的内容数组
  var booklist = result.getElementsByTagName("booklist");
        var name = books[1].getElementsByTagName("name")[0];
        alert(name.innerHTML);
    }
}
xhr.open("get","books.xml",true);
xhr.send();

key point:

  1. Obtaining an array of labels: getElementsBayTagName () returns an array of the class, not carrying an array using JavaScript API
  2. Read the label content: TagName.innerHTML

四, Ajax

Ajax (Asynchoronous Javascript And the Xml) using Asynchronous JavaScript object is provided to the asynchronous send a request to the server, and receive data back in response. It can change the layout without refreshing the effect of the content of the page.

2.1 asynchronous request step

  1. Create an asynchronous objects
  2. Binding listen for events (accepting requests)
  3. Open Link (creation request)
  4. send request

2.2 asynchronous object properties and methods

  1. readyState property

    State value The role of the state
    0 Request uninitialized
    1 Server connection request is sent
    2 Receiving a response header
    3 Receiving a response body
    4 In response to successfully receiving the data
  2. statu server response status code attribute

  3. onreadystatechange event listener status is automatically activated when the readyState change

  4. open ([method], [url], [isAsyn]) create request function

  5. send ([body]) transmission request function

  6. abort () function cancellation request

  7. getAllResponseHeader () Get all response headers

  8. the getResponseHeader () Gets performed in response header

  9. the setRequestHeader () setting request HTTP header

  • Ajax GET request method
//1.创建异步对象
var xhr = new XMLHttpRequest();
//2.绑定监听事件
xhr.onreadystatechange = function(){
    if(xhr.readyState ==4 && xhr.status == 200){
        //执行相关操作的代码
        var result = xhr.responseText;
        alert(result);
    }
}
//3.打开链接
var url = "/test/getajax?uname="+uname.value+"&upwd="+upwd.value;//拼接URL字符串
xhr.oprn("get",url,true);
//4.发送请求
xhr.send();
  • Ajax POST request method
  • postuser.html
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>PostUser</title>
</head>
<body>
	<input type="text" id="uname" name="uname">
	<input type="submit" value="查询" onclick="query()">
	<div id = "show"></div>

	<script>
		var show = document.getElementById("show");
		function query(){
			//创异步对象
			var xhr = new XMLHttpRequest();
			//绑定监听事件
			xhr.onreadystatechange = function(){
				if (xhr.readyState == 4 && xhr.status == 200){
					show.innerHTML = xhr.responseText;
			}
		} 
		var url = "/app/query";
		//打开链接,以post方式
		xhr.open("post",url,true);
		//设置请求头文件参数
		xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
		//拼接请求主体
		var formdata = "uname="+uname.value;
		//发送带有请求主体的请求
		xhr.send(formdata);
	}
	
	</script>
</body>
</html>	

  • server.js
const express = require('express');
//导入路由文件
const querytxt = require('./routes/query.js');
//创建服务器
var server = express();
//设置端口号
server.listen(3000);
//挂载静态资源目录
server.use(express.static('./public'));
//挂载/query 路由
server.use('/app',querytxt);// '/query'
  • query.js
const express = require('express');
//导入mysql模块
const mysql = require('mysql');
//导入请求主体处理模块
const bodyParser = require('body-parser');
//创建空路由
var router = express.Router();
//设置使用json解析
 router.use(bodyParser.json());
// 创建 application/x-www-form-urlencoded 编码解析
 router.use(bodyParser.urlencoded({extended:false}));
//创建数据库连接池
var pool = mysql.createPool({
	host:'127.0.0.1',
	port:'3306',
	user:'root',
	password:'741852',
	database:'tedu',
	connectionLimit:10
});
//post方法查询数据库名称路由
router.post('/query',(req,res)=>{
	var $uname = req.body.uname;
	var sql = "select uname from login where uname=?";
 	pool.query(sql,[$uname],(err,result)=>{
  		if(err) throw err;
  		if(result.length > 0){
  			res.send("用户存在");
  		}else{
  			res.send("用户不存在");
  		}
  	});
});
//导出路由
module.exports = router;

Optimized Ajax code to view the JavaScript DOM Technology Column 7 articles

Published 113 original articles · won praise 175 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_42873753/article/details/104571608