Web前端-Ajax基础技术(下)

Web前端-Ajax基础技术(下)

Web前端-Ajax基础技术(下)

你要明白ajax是什么,怎么使用?

ajaxweb程序是将信息放入公共的服务器,让所有网络用户可以通过浏览器进行访问。

浏览器发送请求,获取服务器的数据:

地址栏输入地址,表单提交,特定的hrefsrc属性。

<script>
var xhr = new XMLHttpRequest();
xhr.open('GET', 'test.php');
xhr.send()
xhr.onreadystatechange = function() {
 if(this.readyState != 4) return
 var res = JSON.parse(this.responseText);
 // res 服务器返回的数据
 var data = res.data;
 for(var i = 0; i<data.length; i++){
  
 }
}

ajax上手:

// 创建一个XMLHttpRequest类型的对象
var xhr = new XMLHttpRequest();
// 打开一个网址的连接
xhr.open('GET', './time.php');
// 发送一次请求
xhr.send(null);
// 处理网页呈现后的操作
xhr.onreadystatechange = function() {
 if(this.readyState === 4) {
  console.log(this);
 }
}

效果

readyState

0 xhr被创建,未调用open()方法
1 open()方法被调用,建立了连接
2 send()方法被调用,可以获取状态行和响应头
3 响应体下载中,responseTest属性可能已经包含部分数据
4 响应体下载完成,直接使用responseText

http请求:

// 设置请求报文的请求行
xhr.open('GET', './time.php');
// 设置请求头
xhr.setRequestHeader('Accept', 'text/plain');
// 设置请求体
xhr.send(null);
xhr.onreadystatechange = function() {
 if(this.readyState === 4) {
  // 获取响应状态码
  console.log(this.status);
 // 获取响应状态描述
  console.log(this.statusText);
 // 获取响应头信息
  console.log(this.getResponseHeader('Content-Type')); // 指定响应头
  console.log(this.getAllResponeseHeaders()); // 全部响应头
  // 获取响应体
  console.log(this.responseText) // 文本形式
  console.log(this.responseXML) // xml
 }
}

post请求:

var xhr = new XMLHttpRequest();
// open方法的第一个参数作用, 设置请求的method
xhr.open('POST', './add.php');
// 设置请求体格式
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('key=value');
xhr.onreadystatechange = function() {
 if(this.readyState === 4) {
  console.log(this.responseText);
 }
}

异步同步:

// 异步
console.log('before ajax');
var xhr = new XMLHttpRequest();
xhr.open('GET', './time.php', true);
xhr.send(null);
xhr.onreadystatechange = function() {
 if(this.readyState === 4){
  console.log('request done');
 }
}
console.log('after ajax');

// 同步
console.log('before ajax');
var xhr = new XMLHttpRequest();
xhr.open('GET', './time.php', false);
xhr.send(null);
xhr.onreadystatechange = function() {
 if(this.readyState === 4){
  console.log('request done');
 }
}
xhr.send(null);
console.log('after ajax');

响应类型:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'test.php');
xhr.send();
// 请求代理对象,响应类型
xhr.responseType = 'json';
xhr.onreadystatechange = function() {
 if(this.readyState != 4) return;
 console.log(this);
}

服务器响应,使用 XMLHttpRequest 对象的responseTextresponseXML属性。

responseText获取字符串形式的响应数据,responseXML获取xml形式的响应数据。

responseText

document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');

模板引擎:

artTemplate: https://aui.github.io/art-template/

art-template是一个简约,超快的模板引擎,采用作用域声明的技术来优化模板渲染速度。

安装:

npm install art-template --save

下载:

lib/template-web.js
<script src="template-web.js" >
</script>
// 封装
function ajax(method, url, params) {

var xhr = new XMLHttpRequest();
xhr.open(method, url);
 
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
params = params || null;
xhr.send(params);
xhr.onreadystatechange=function(){
 if(this.readyState != 4) return
 console.log(this.responseText);
} 

}

ajax('GET', 'time.php', 'key=value');

function ajax(method, url, params) {

var xhr = new XMLHttpRequest();
if(method === 'GET'){
 url += "?" + params;
}
xhr.open(method, url);

var data = null;
if(method === 'POST') {
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
data = params
}

xhr.send(data);
xhr.onreadystatechange=function(){
 if(this.readyState != 4) return
 console.log(this.responseText);
} 

}
// 传对象
function ajax(method, url, params) {

var xhr = new XMLHttpRequest();
if(typeof params === 'object'){
 var tempArr = [];
 for(var key in params){
  var value = params[key];
  tempArr.push(key + "=" + value);
 } 
 params = tempArr.join('&');
}

if(method === 'GET'){
 url += "?" + params;
}
xhr.open(method, url);

var data = null;
if(method === 'POST') {
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
data = params
}

xhr.send(data);
xhr.onreadystatechange=function(){
 if(this.readyState != 4) return
 console.log(this.responseText);
} 

}
function ajax(method, url, params, done) {
method = method.toUpperCase();
var xhr = new XMLHttpRequest();
if(typeof params === 'object'){
 var tempArr = [];
 for(var key in params){
  var value = params[key];
  tempArr.push(key + "=" + value);
 } 
 params = tempArr.join('&');
} 

if(method === 'GET'){
 url += "?" + params;
}
xhr.open(method, url, false);

var data = null;
if(method === 'POST') {
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
data = params
}

xhr.onreadystatechange=function(){
 if(this.readyState != 4) return
 // console.log(this.responseText);
 done(this.responseText);
} 
 
xhr.send(data);
}

var ondone = function(res) {
 console.log(res);
}

回调:
效果

<script>
 function foo() {
  setTimeout(function(){
   return Date.now();
  }, 1000);
 }
 
 var time = foo()
</script>

jquery中的ajax

https://www.jquery123.com/category/ajax/
function ajax(method, url, params, done) {
// 统一转换大写
 method = method.toUpperCase();
// urlencoded
 var pairs = [];
 for(var key in params) {
  pairs.push(key+"="+params[key]);
 }
 var querystring = pairs.join('&');
 var xhr = window.XMLHttpRequest?new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');

xhr.addEventListener('readystatechange',function(){
 
}
}
<script src="jquery.js"></script>
<script>
 $.ajax('./time.php', {
  type: 'post', // method 请求方法
 success: function(res) {
  console.log(res);
 }
 }
</script>

$.ajax({
 url: 'time.php',
 type: 'post',
 data: { id: 1, name: '张三' },
 success: function(res) {
  console.log(res);
 }
})
$.ajax({
 url: 'json.php',
 type: 'get',
 dataType: 'json',
 success: function(res) {
  console.log(res)
 }
})

ajax回调事件:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title></title>
</head>
<body>
 <script src="jquery.js"></script>
 <script>
  $.ajax({
   url: 'time.php',
   type: 'get',
   beforeSend: function(xhr) {
    console.log('beforeSend', xhr);
   },
   success: function(res) {
    console.log(res);
   },
   error: function(xhr) {
    console.log(xhr);
   },
   complete: function(xhr) {
    console.log(xhr);
   }
  })
 </script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title></title>
</head>
<body>
 <script src="jquery.js"></script>
 <script>
  var xhr = new XMLHttpRequest();
  xhr.open('get','time.php');
  xhr.send()
  xhr.onreadystatechange = function() {
   if(this.readyState != 4) return
   console.log(this.responseText);
  }
 </script>
</body>
</html>
<script src="jquery.js"></script>
<script>
$.get('time.php', function(res){
  console.log(res);
})

$.get('time.php', { id: 1 }, function(res) {
 console.log(res);
})

$.post('time.php', { id: 1 }, function(res) {
 console.log(res);
})
</script>
.ajaxComplete()
当ajax请求完成后注册一个回调函数
.ajaxError()
ajax请求出错
.ajaxSend()
ajax请求发送之前绑定一个要执行的函数
.ajaxStart()
在ajax请求刚开始时执行一个处理函数
.ajaxStop()
在ajax请求完成时执行一个处理函数
.ajaxSuccess()
绑定一个函数当ajax请求成功完成时执行
jQuery.ajax()
执行一个异步的http(ajax)请求
jQuery.ajaxPerfilter()
在每个请求之前被发送和$.ajax()处理它们前处理
jQuery.ajaxSetup()
为以后要用到的ajax请求设置默认的值
jQuery.ajaxTransport()
创建一个对象
jQuery.get()
使用一个http get请求从服务器加载数据
jQuery.getJSON()
jQuery.getScript()
GET请求从服务器加载并执行一个 JavaScript 文件
jQuery.post() 请求从服务器加载数据

跨域:
同源,域名,协议,端口,完全相同,同源的相互通过ajax的方式进行请求。
不同源地址之间,不能相互发送ajax请求。

$.get('http://', function(res) {
 console.log(res);
})
<!DOCTYPE html>
<head>
 <meta charset = "UTF-8">
 <title>AJAX基础回顾</title>
</head>
<body>
 <script>
 var xhr = new XMLHttpRequest();
 xhr.open('GET', 'test.php');
 xhr.responseType='json';
 xhr.onreadystatechange = function() {
  if(this.readyState !== 4) return
  console.log(this.response);
 }
 </script>
</body>
</html>
$.get('http://...', function(res){
 console.log(res);
})
<meta http-equiv="Content-Type" content="text/html; charset=gb2312"/>
<meta http-equiv="Content-Language" content="zh-cn"/>
<meta name="robots" content="all"/>
<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon"/>
var link = document.createElement('link');
link.rel = 'stylesheet';
link.href = 'http//...';
document.body.appendChild(link);

var script = document.createElement('script');
script.src = 'http://...';
document.body.appendChild(script);

jsonp原理:
json是借助script标签发送跨域请求的技巧。
原理是在客户端借助script标签请求服务端的一个动态网页,服务端的这个动态网页返回一段带有函数调用的javascript全局函数调用的脚本,将原本需要返回给客户端的数据传递进去。

$.ajax({
 url: 'http://...',
 dataType: 'json',
 success: function(res) {
  console.log(res);
 }
})

结言

好了,欢迎在留言区留言,与大家分享你的经验和心得。

感谢你学习今天的内容,如果你觉得这篇文章对你有帮助的话,也欢迎把它分享给更多的朋友,感谢。

作者简介

达叔,理工男,简书作者&全栈工程师,感性理性兼备的写作者,个人独立开发者,我相信你也可以!阅读他的文章,会上瘾!,帮你成为更好的自己。长按下方二维码可关注,欢迎分享,置顶尤佳。

努力努力再努力Jeskson

猜你喜欢

转载自www.cnblogs.com/dashucoding/p/10549697.html