创建ajax
1、首先创建ajax ,将 ajax在文档中用js文档保存起来
function ajax(option){
var Method = option.method || "GET"
var data = option.data || {}
var url=option.url
var srt="?"
for (var key in data){
srt+=key+"="+data[key]+"&"
}
srt=srt.slice(0,srt.length-1)
url +=srt
console.log(url)
// 1.创建ajax对象
var xhr = new XMLHttpRequest()
// 2.建立连接
xhr.open(Method, url,true)
// 3.发送请求
xhr.send()
// 4.监听数据回来
xhr.onreadystatechange=function(){
// xhr.readyState === 4 意味这服务器返回数据
// xhr.status == 200 服务器返回正确的数据
if( xhr.readyState === 4 && xhr.status == 200 ){
var res = JSON.parse(xhr.responseText)
option.success(res)
}
}
}
1567569958961.png
2、在html文档中渲染
用script标签的src将ajax.js引入到文档中
<script src="../js/ajax.js"></script>
将创建的ajax调用
ajax({
url:"http://132.232.94.151:3000/api/film/getList",
success: function(res){
console.log(res)
var films=res.films
var str=""
for(var i=0 ; i<films.length;i++){
var div=`
<a href="../html/dianying.html?filmId=${films[i].filmId}">
<div class="info-c">
<img class="img" src="${films[i].poster}" alt="">
<div class="info-cc">
<div class="item">
<span>${films[i].name}</span>
<span>${films[i].filmType}</span>
</div>
<span class="text">主演:${films[i].actorStr}</span>
<span class="text1">${films[i].nation} | ${films[i].runtime}分钟</span>
</div>
<div class="info-right">
<span>购票</span>
</div>
</div>
</a>
`
str+=div
}
document.querySelector(".info").innerHTML=str
},
data:{
pageNum:1,
pageSize:10
}
})
网友评论