ES6
const getJSON = function(url,type,data) {
const promise = new Promise(function(resolve, reject){
const handler = function() {
if (this.readyState !== 4) {
return;
};
if (this.status === 200) {
resolve(this.response);
} else {
reject(new Error(this.statusText));
}
};
const client = new XMLHttpRequest();
client.open(type, url);
client.onreadystatechange = handler;
client.responseType = "json";
if(type=='get'){
client.send();
}else {
client.setRequestHeader("Content-Type","application/json");//data只能是JSON字符串
client.send(JSON.stringify(data)) //post请求传入string
}
});
return promise;
};
$(function() {
$("button").click(function() {
getJSON('http://localhost:3000/info','get')
.then(function(json) {
//success
console.log('ok');
})
.catch(function(error) {
console.error('出错了', error);
});
});
//JQUERY 1.5.0返回的是xhr对象 高于1.5.0返回的deferred对象
})
js实现简单留言板
/**
Simple Server for web api test.
*/
/**Connect是一个node中间件(middleware)框架。
如果把一个http处理过程比作是污水处理,中间件就像是一层层的过滤网。
每个中间件在http处理过程中通过改写request或(和)response的数据、状态,实现了特定的功能。
中间件就是类似于一个过滤器的东西,在客户端和应用程序之间的一个处理请求和响应的的方法。*/
var connect = require('connect'); //创建连接
var bodyParser = require('body-parser'); //body解析
var app = connect()
.use(bodyParser.json()) //JSON解析
.use(bodyParser.urlencoded({extended: true}))
//use()方法还有一个可选的路径字符串,对传入请求的URL的开始匹配。
//use方法来维护一个中间件队列
.use(function (req, res, next) {
//跨域处理
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*'); //允许任何源
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); //允许任何方法
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,X-Session-Token'); //允许任何类型
res.writeHead(200, {"Content-Type": "text/plain;charset=utf-8"}); //utf-8转码
next(); //next 方法就是一个递归调用
})
.use('/add', function(req, res, next) {
console.log(req.body);
var data = [];
data.push(req.body);
console.log(data);
res.end(JSON.stringify(data));
next();
})
.use('/map/add1', function(req, res, next) {
var data={
"code": "200",
"msg": "success",
"result": {
"id":1,
}
};
res.end(JSON.stringify(data));
next(); //
})
.use('/map/add2', function(req, res, next) {
var data={
"code": "200",
"msg": "success",
"result": {
"name": "sonia",
"content": "广告投放1"
}
};
res.end(JSON.stringify(data));
next(); //
})
.listen(3000);
console.log('Server started on port 3000.');
const getJSON = function(url,type, data) {
const promise = new Promise(function(resolve, reject){
const handler = function() {
if (this.readyState !== 4) {
return;
};
if (this.status === 200) {
resolve(this.response);
} else {
reject(new Error(this.statusText));
}
};
const client = new XMLHttpRequest();
client.open(type, url);
client.onreadystatechange = handler;
client.responseType = "json";
if(type =='get'){
client.send();
}else {
client.setRequestHeader("Content-Type", "application/json");
client.send(JSON.stringify(data));
}
});
return promise;
};
$(function() {
//添加数据
$(".submit").click(() => {
let _name = $(".name").val(),
_message = $(".message").val();
if(_name =='' || _message =='') {
alert('请输入信息!');
return false;
}
$(".name,.message").val("");
add(_name,_message);
});
let add = (name, message) => {
getJSON("http:localhost:3000/add",'post', {name: name, message: message})
.then(function(json) {
for (let i=0; i${json[i].name}说:${json[i].message}
`);
}
}, function(error) {
console.error('出错了', error);
});
};
//列表显示
let listShow = () => {
//原生promise
/*getJSON("/map/get",'get').then(function(d) {
_showList(d);
}, function(error) {
console.error('出错了', error);
});*/
//$.ajax() 低于1.5.0版本的jQuery,返回的是XHR对象,高于1.5.0版本,返回的是deferred对象,可以进行链式操作。
// 链式写法
let list = $(".messageList"),str = "";
$.ajax({url:"http:localhost:3000/map/get",dataType:"json",type:"get"})
.done(function(d){
})
.fail(function(){ alert("出错啦!"); });
};
//查询数据
//链式写法 串行
$(".queryThen").click(()=> queryThen());
let queryThen = ()=> {
$.ajax({url:"http:localhost:3000/map/add1",dataType:"json",type:"get"})
.then(data => {
return $.ajax({url:"http:localhost:3000/map/add2",dataType:"json",type:"post",data:{id:data.result.id}})
//return $.get("http:localhost:3000/map/add2", data.result.id);
})
.then(data => {
alert(data);
})
.catch(error=>{
console.log(error);
})
};
let addPromise1 = new Promise((resolve,reject) => {
getJSON("http:localhost:3000/map/add1",'get').then(function(d) {
resolve(d);
}, function(error) {
console.error('出错了', error);
});
});
let addPromise2 = new Promise((resolve,reject) => {
getJSON("http:localhost:3000/map/add2",'get').then(function(d) {
resolve(d);
}, function(error) {
console.error('出错了', error);
});
});
// 并行 when 多个请求完成后返回
$(".queryWhen").click(()=> queryWhen());
let queryWhen = ()=> {
/*$.when($.ajax({url:"/map/add1",dataType:"json",type:"get"}), $.ajax({url:"/map/add2",dataType:"json",type:"get"}))
.then((data1,data2) => {
console.log(data1[0]);
console.log(data2[0]);
}, () => { alert("出错啦!"); });*/
Promise.all([
addPromise1,
addPromise2
]).then(([add1,add2])=>{
console.log(add1);
console.log(add2);
}, function(error) {
console.error('出错了', error);
});
};
})