编写类似jquery的library
编写Get 方法+Callback
libray.js
将open,load,send放入一个methods中。
function easyHTTP(){
this.http = new XMLHttpRequest();
}
//Make an HTTP GET Request
easyHTTP.prototype.get = function(url,callback){
this.http.open('GET',url,true);
let self = this;
this.http.onload=function(){
//若用this,则当前的this不会easyHTTP对象,变为this.http对象
if(self.http.status===200){
callback(null,self.http.responseText);
}else{
callback('Error: '+ self.http.status);
}
}
this.http.send();
}
Get single post
//GET single Post
http.get('https://jsonplaceholder.typicode.com/posts/1',function(err,response){
if(err){
console.log(err);
}else{
console.log(response);
}
});
app.py
传入callback函数,防止get的速度慢于return,导致return null;
const http = new easyHTTP;
//Get Posts
http.get('https://jsonplaceholder.typicode.com/posts',function(err,response){
if(err){
console.log(err);
}else{
console.log(response);
}
});
//callback方法
POST请求
app.js
调用post请求+callback
//Create Data
const data = {
title:'Custom Post',
body:'this is a custom post'
};
//Create Post
http.post('https://jsonplaceholder.typicode.com/posts',data,function(err,post){
if(err){
console.log(err);
}else{
console.log(post);
}
}); //id 自动为101
library.js
设置post请求;
//Make an HTTP POST Request
easyHTTP.prototype.post = function(url,data,callback){ //post 可能需要传入data
this.http.open("POST",url,true);
//设置content的type
this.http.setRequestHeader(`Content-type`,`application/json`);
let self=this;
this.http.onload=function(){
callback(null,self.http.responseText);
}
this.http.send(JSON.stringify(data)); //把object变为string再send
}
PUT请求
app.js
//Create Data
const data = {
title:'Custom Post',
body:'this is a custom post'
};
//Update Post
http.put('https://jsonplaceholder.typicode.com/posts/1',data,function(err,post){
if(err){
console.log(err);
}else{
console.log(post);
}
}); //更新了该url的data
library.js
//Make an HTTP PUT Request
easyHTTP.prototype.put = function(url,data,callback){ //post 可能需要传入data
this.http.open("PUT",url,true);
//设置content的type
this.http.setRequestHeader(`Content-type`,`application/json`);
let self=this;
this.http.onload=function(){
callback(null,self.http.responseText);
}
this.http.send(JSON.stringify(data)); //把object变为string再send
}
Delete请求
app.js
//Make an HTTP DELETE REQUEST
http.delete('https://jsonplaceholder.typicode.com/posts/1',function(err,response){
if(err){
console.log(err);
}else{
console.log(response);
}
});
library.js
//Make an HTTP DELETE Request
easyHTTP.prototype.delete = function(url,callback){
this.http.open('DELETE',url,true);
let self = this;
this.http.onload=function(){
if(self.http.status===200){
callback(null,`Post deleted`); //返回空:已删除
}else{
callback('Error: '+ self.http.status);
}
}
this.http.send();
}
本文介绍了一个简易的HTTP库实现,包括GET、POST、PUT和DELETE请求的处理方式,以及如何使用回调函数进行异步操作。通过实例展示了如何发送请求、处理响应及错误。
586

被折叠的 条评论
为什么被折叠?



