什么是ajax
ajax是一种技术方案,但并不是一种新技术。它依赖的是现有的CSS/HTML/JavaScript,而其中最核心的依赖是浏览器提供的XMLHttpRequest对象,是这个对象使得浏览器可以发出HTTP请求与接收HTTP响应。实现在页面不刷新的情况下和服务端进行数据交互。
如何mock数据
- http-server:使用 http-server node工具启动一个静态服务器
- server-mock:使用 server-mock node工具启动一个能处理静态文件和动态路由的服务器
- 手写一个服务器:链接
-
线上mock数据:
- 使用http://easy-mock.com/
- 使用http://rapapi.org/org/index.do
- 使用 server-mock
实例代码
- GET类型的ajax:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://api.jirengu.com/weather.php', true);
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if((xhr.status >= 200 && xhr.status <= 300) || xhr.status === 304){
//成功了
console.log(xhr.responseText);
} else{
console.log('服务器异常');
}
}
};
xhr.onerror = function(){
console.log('服务器异常');
};
xhr.send();
//另一种写法
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://api.jirengu.com/weather.php', true);
xhr.onload = function(){
if((xhr.status >= 200 && xhr.status <= 300) || xhr.status === 304){
//成功了
console.log(xhr.responseText);
} else{
console.log('服务器异常');
}
};
xhr.onerror = function(){
console.log('服务器异常');
};
xhr.send();
- POST类型的ajax:
var xhr = new XMLHttpRequest();
xhr.timeout = 3000; //可选,设置xhr请求的超时时间
xhr.open('POST', '/register', true);
xhr.onload = function(e){
if((xhr.status >= 200 && xhr.status <= 300) || xhr.status === 304){
//成功了
console.log(this.responseText);
}
};
//可选
xhr.onerror = function(){
console.log('服务器异常');
};
//可选
xhr.ontimeout = function(){
console.log('请求超时');
}
xhr.send('username=jirengu&password=123456');
POST类型可将用户信息放进send()里
- 封装一个ajax:
function ajax(options){
var url = options.url,
type = options.type || 'GET',
dataType = options.dataType || 'json',
onsuccess = options.onsucess || function(){},
onerror = options.onerror || function(){},
data = options.data || {};
var dataStr = [];
for(var key in data){
dataStr.push(key + '=' +data[key]);
}
dataStr = dataStr.join('&');
if(type === 'GET'){
url += '?' + dataStr;
}
var xhr = new XMLHttpRequest();
xhr.open(type, url, true);
xhr.onload = function(){
if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
if(dataType === 'json'){
onsuccess(JSON.parse(xhr.reponseText));
}else{
onsuccess(xhr.responseText);
}
}else{
onerror();
}
};
xhr.onerror = onerror;
if(type === 'POST'){
xhr.send(dataStr);
}else{
xhr.send();
}
}
ajax({
url: 'http://api.jirengu.com/weather.php',
data: {
city: '北京'
},
onsuccess: function(ret){
console.log(ret);
},
onerror: function(){
console.log('服务器异常');
}
});