1 在文件夹里面新建一个js
<script>
var url = 'http://47.108.197.28:8000/book'
//var url ="http:47.108.197.28:3000/banner"
function $ajax(url,success){
var xhr = new XMLHttpRequest();
xhr.open("get",url,true);
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.responseText ==4 && xhr.status==200){
var res = JSON.parse(xhr.responseText);
success(res)
}
}
}
$ajax(url,res=>{
console.log(res)
})
回调函数
<script>
// function $ajax(callback){
// var res = "hello word"
// callback(res);
// }
// var s =$ajax(res=>{
// console.log(res)
// })
//写在本子上
function $ajax({
success
}){
var res = "hello word"
success(res);
}
$ajax({
success:res=>{
console.log(res)
}
})
</script>
示例
<script>
/*
函数的参数
*/
// function ajax(url,method,c){
// console.log(url);
// console.log(method);
// console.log(c)
// }
// ajax("http","get",1)
// ajax(1,"http","get")
//如果参数过多,可以传对象
function ajax({
url,
method,
c
}){
console.log(url);
console.log(method);
console.log(c)
}
ajax({
method:"get"
})
</script>
<script>
/*
如何实现ajax
*/
var url = 'http://47.108.197.28:8000/book'
// var success = function(res){
// console.log(res)
// }
function go(){
var res = "hello word"
success(res)
}
go(res=>{
console.log(res)
})
</script>
练习
<script>
var banner = 'http://47.108.197.28:3000/banner'
var xhr =new XMLHttpRequest();
xhr.open("get",banner,true)
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.readyState==4 && xhr.status==200){
console.log(xhr.responseText)
var res = JSON.parse(xhr.responseText)
console.log(res)
}
}
</script>