ajax四部曲
- 新建对象
- open配置请求参数
- send发送请求
- 事件监听
var http = new XMLHttpRequest();
http.open("GET", "http://localhost:8787/getNews?page=1&count=5", true)
http.send();
http.addEventListener("load", function () {
console.log(http.responseText)
})
ajax封装方法
function ajax(ops) {
var http = new XMLHttpRequest();
let type = ops.type || "get";
if (type.toLowerCase() == "get") {
http.open("GET", ops.url + "?" + obj2str(ops.data), true)
http.send();
} else {
http.open("POST", ops.url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(obj2str(ops.data));
}
http.addEventListener("readystatechange", function () {
if (http.readyState == 4 && http.status == 200) {
ops.success && ops.success(http.responseText)
}
})
}
ajax({
url: "...",
data: {
page: 1,
count: 5
},
success: function (res) {
console.log(res)
},
type: "get"
})
let obj2str = (data) => {
let arr = [];
for (var k in data) {
arr.push(item + '=' + data[item]);
}
return arr.join("&");
}
ajax创建服务器及使用(利用koa框架)
- 安装nodejs
- 添加模块依赖:
方式一:直接拷贝package.json,终端运行 npm i ,会自动添加模块依赖
方式二:创建描述文件 npm i ,再自己装:npm i koa koa-router koa-static -S-D - node 文件名 : 启动服务端命令
- nodemon 文件名:这种方式启动服务端,每次修改不用再运行命令
安装nodemon: npm i nodemon -g - 通过配置的端口号,在浏览器访问,查看是否成功
创建服务器
引入各个模块并对请求地址等进行设置
const Koa = require("koa");
const static = require("koa-static");
const Router = require("koa-router");
let app = new Koa();
let router = new Router();
app.use(static(__dirname + "/static"));
router.all("/", ctx => {
ctx.body = "看来你想请求8787端口";
})
router.all("/getNews", ctx => {
let arr = [
{ title: "标题一", content: "内容一" },
{ title: "标题二", content: "内容二" },
{ title: "标题三", content: "内容三" },
{ title: "标题四", content: "内容四" },
{ title: "标题五", content: "内容五" },
{ title: "标题六", content: "内容六" },
{ title: "标题七", content: "内容七" },
{ title: "标题八", content: "内容八" },
{ title: "标题九", content: "内容九" },
{ title: "标题十", content: "内容十" }];
let page = ctx.query.page || 1;
let count = ctx.query.count || 5;
let newArr = arr.slice( (page-1)*count, count*page);
ctx.body = {data:newArr,totalPage:Math.ceil(arr.length/count)};
})
app.use(router.routes());
app.listen(8787);
自己的页面放在static文件下,因为上面是这么配置的
<script>
let obj2str = (data)=>{
let arr = [];
for(let item in data){
arr.push(item+'='+data[item]);
}
return arr.join('&');
}
function ajax(ops){
console.log(obj2str(ops.data));
let http = new XMLHttpRequest();
let type = ops.type || 'get';
console.log(type)
if(type.toLowerCase() == 'get'){
http.open('GET',ops.url+'?'+obj2str(ops.data),true);
http.send();
}else{
http.open('POST',ops.url+'?'+obj2str(ops.data),true);
http.setRequestHeader('Content-type','application/x-www-form-urlencoded');
http.send();
}
http.addEventListener('readystatechange',function(){
console.log(http.readyState)
console.log(http.status)
if(http.readyState==4 && http.status==200){
ops.success&&ops.success(http.responseText,1)
}
})
}
ajax({
url:'http://localhost:8787/getNews',
type:'post',
data:{
page:1,
count:3
},
success:function(res){
console.log(res)
}
});
ajax跨域
- 需要配置两个服务器环境
- 三种方式实现跨域:
1、jsonp
2、cors
3、开代理(需要再安装模块依赖 npm i koa-server-http-proxy) - 这里我就用代理来实现,现在代理最常用
自己的html文件
button class="btn">点击发送ajax</button>
<script>
let btn = document.querySelector(".btn");
btn.addEventListener("click", () => {
let xhr = new XMLHttpRequest();
xhr.open("get", "/api/myproxy", true);
xhr.addEventListener("load", () => {
console.log(xhr.responseText);
})
xhr.send();
})
</script>
创建服务器
本台服务器端口号为3000
const Koa = require("koa");
const Router = require("koa-router");
const static = require("koa-static");
let app = new Koa();
let router = new Router();
let koaServerhttpProxy = require("koa-server-http-proxy");
app.use(static(__dirname + "/static"))
app.use(koaServerhttpProxy('/api', {
target: 'http://localhost:4000',
pathRewrite: { '^/api': '' },
changeOrigin: true
}))
router.get("/test", ctx => {
ctx.body = "hello3000";
});
router.get("/myproxy", ctx => {
ctx.body = {
info: "3000端口",
status: 1
}
})
app.use(router.routes());
app.listen(3000);
创建服务器
本台服务器端口号为4000
const Koa = require("koa");
const Router = require("koa-router");
const static = require("koa-static");
let app = new Koa();
let router = new Router();
app.use(static(__dirname + "/static"))
router.get("/test", ctx => {
ctx.body = "hello4000";
});
router.get("/myproxy", ctx => {
ctx.body = [{
tittle: "有点东西1",
id: 1
}, {
tittle: "优点东西2",
id: 2
}]
})
app.use(router.routes());
app.listen(4000);