<!-- ajax
1.客户端向服务器获取数据的一种技术
2.是一种在无需重新加载整个网页的情况下,能够局部更新网页的技术
-->
<!-- 如何实现 -->
<script>
var url ="http://192.168.4.18:8000/"
/* 1.创建ajax核心对象 */
var xhr = new XMLHttpRequest();
/* 2.与服务建立连接(method,url,async) */
xhr.open("get",url,true)
/* 3.发送请求 */
xhr.send()
/* 4.响应 */
xhr.onreadystatechange = function(){
if(xhr.status == 200 && xhr.readyState ==4){
var res =JSON.parse(xhr.responseText) ;
console.log(res)
}
}
</script>
封装ajax
function ajax({
url,
method,
success
}){
var xhr = new XMLHttpRequest()
xhr.open(method,url,true)
xhr.send()
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
var res = JSON.parse(xhr.responseText);
success(res);
}
}
}
var url = "http://192.168.4.18:8000/"
ajax({
url,
method:"get",
success:res=>{
console.log(res)
}
})
渲染列表
<body>
<div class="app">
<div class="left">
</div>
<div class="right">
</div>
</div>
<script>
/* 1.渲染列表 */
var listUrl = "http://192.168.4.18:8000/";
ajax({
url: listUrl,
method: "get",
success: res => {
var arr = res.result;
arr.forEach((item, index) => {
var {pic,title,raiting,slogo,evaluate,labels} = item;
var sum =labels.join("/")
var htmlItem = `
<div class="item">
<span>${index+1}</span>
<img src=${pic} alt="">
<div>
<p class="title">${title}</p>
<p>${sum}</p>
<p><span>评分:${raiting}</span> <span> ${evaluate}人评价</span></p>
<p>${slogo}</p>
</div>
</div>
`
$(".left").append(htmlItem);
})
}
})
</script>
封装的http
var baseUrl ="http://192.168.4.18:3000/"
function ajax({
url,
method = "get",
success
}){
var xhr = new XMLHttpRequest();
xhr.open(method,url=baseUrl+url,true);
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
var result = JSON.parse(xhr.responseText);
success(result)
}
}
}
/* banner的http为例 */
function httpBanner(callback){
ajax({
url:"banner",
success:res=>{
callback(res)
}
})
}
function httpList(callback){
ajax({
url:"top/playlist?cat=华语",
success:res=>{
callback(res);
}
})
}
点击事件跳转
<div class="item" data-aid="1234">
hello world 1
</div>
<div class="item" data-aid="1524">
hello world 1
</div>
<script>
$(".item").click(function(event){
console.log(event.target.dataset.aid)
})
</script>
页面之间跳转传值
<input type="text" id="input">
<script>
var input = document.getElementById("input");
input.onkeydown = function(event){
if(event.keyCode == 13){
console.log(this.value);
location.href = `search.html?s=${this.value}`
}
}
</script>
<input type="text">
<p>搜索</p>
<script>
var a = location.search.split("=")[1]
var c = decodeURIComponent(a)
console.log(c)
</script>