ajax学习实例,ajax学习

什么是ajax

ajax是一种技术方案,但并不是一种新技术。它依赖的是现有的CSS/HTML/JavaScript,而其中最核心的依赖是浏览器提供的XMLHttpRequest对象,是这个对象使得浏览器可以发出HTTP请求与接收HTTP响应。实现在页面不刷新的情况下和服务端进行数据交互。

如何mock数据

http-server:使用 http-server node工具启动一个静态服务器

server-mock:使用 server-mock node工具启动一个能处理静态文件和动态路由的服务器

手写一个服务器:链接

实例代码

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('服务器异常');

}

});

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值