下载企业网站,安徽六安职业技术学院,网站是否能够被恶意镜像,装修公司大全ajax请求的过程 我们平时输入的网址#xff0c;比如www.baidu.com#xff0c;就会被解析成14.215.177.39这一串数字#xff0c;然后发送请求给后台服务器#xff08;客户端发送http请求#xff09;。 服务器会确认你发送的是什么请求#xff0c;需要请求什么东西#xf… ajax请求的过程 我们平时输入的网址比如www.baidu.com就会被解析成14.215.177.39这一串数字然后发送请求给后台服务器客户端发送http请求。 服务器会确认你发送的是什么请求需要请求什么东西三次握手。 拿到服务器返回的数据后就传回给页面了这时候就跟服务器告别四次挥手。 传回给浏览器渲染页面htmlcssjs。 Ajax的实际运作好比做一个定外卖的过程 封装Ajax 1 !DOCTYPE html2 html langen3 head4 meta charsetUTF-85 meta nameviewport contentwidthdevice-width, initial-scale1.06 meta http-equivX-UA-Compatible contentieedge7 titleDocument/title8 /head9 body
10 form
11 input typetext nameurername idusername
12 input typetext nameage idage
13 input typesubmit idsbm value提交
14 /form
15 ol idol/ol
16 button idbtn请求新闻/button
17 !-- Ajax
18 1.浏览器
19 2.Ajax对象
20 3.Ajax.open(method, url, true);
21 4.Ajax.send();
22 5.onreadtstatechage 4
23 6.status 200 403 503 --
24
25 script
26 //请求新闻的监听事件
27 btn.onclick function(){
28 ajaxFunc(GET, ./getNews.php, , showList, true);
29 }
30
31 //请求form表单的监听事件
32 sbm.onclick function(e){
33 e.preventDefault();//取消默认提交form表单的事件
34 var data username username.value age age.value;
35 ajaxFunc(POST, ./post.php, data, showPerson, true);
36 }
37
38
39
40 //封装的Ajax函数
41 function ajaxFunc(method, url, data, callback, flag){
42
43 //创建Ajax对象
44 var xhr null;
45 if(window.XMLHttpRequest){//浏览器兼容
46 xhr new XMLHttpRequest();
47 }else{
48 xhr new ActiveXObject(Microsoft.XMLHttp);
49 }
50
51 method method.toUpperCase();
52 if(method GET){//判断传入的是GET请求还是POST请求
53 //向后端发送请求获取数据
54 xhr.open(method, url, ? data, flag);//请求方式 请求地址 异步请求
55 //把Ajax发送出去
56 xhr.send();
57 }else if(method POST){
58 //向后端发送请求获取数据
59 xhr.open(method, url, flag);//请求方式 请求地址 异步请求
60 //设置请求头
61 xhr.setRequestHeader(Content-type, application/x-www-form-urlencoded);
62 //把Ajax发送出去
63 xhr.send(data);
64 }
65
66 //监听返回的数据 数据解析分为4个阶段 1.读取 2.已读取 3.交互中 4.完成
67 xhr.onreadystatechange function(){ //数据状态改变一次就会触发一次
68 if(xhr.readyState 4){ //数据是不是为4的状态4为响应内容解析完成
69 if(xhr.status 200){
70
71 callback(xhr.responseText);
72 }
73 }
74 }
75 }
76
77 //GET请求的回调函数
78 function showList(data){
79 var value JSON.parse(data);
80 var str ;
81 value.forEach(function(ele, index){
82 str li ele.title - ele.date /li;
83 })
84 ol.innerHTML str;
85 }
86
87
88 //POST请求的回调函数
89 function showPerson(data){
90 alert(data);
91 }
92 /script
93 /body
94 /html ------------------------------------------------------ get:主要用来获取数据的。 post主要用来往后端传数据的 转载于:https://www.cnblogs.com/yangpeixian/p/11117873.html