点击列表跳转详情页
index.css
*{padding: 0;margin: 0;}
.container{
width: 1200px;
margin: 100px auto;
display: flex;
flex-wrap: wrap;
}
.container .product-item{
width: 260px;
height: 440px;
background-color: rgb(242,246,244);
margin-right: 35px;
}
.container .product-item img{
width: 100%;
}
index.html
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>商品列表</title>
<link rel="stylesheet" href="./css/index.css">
<!--
前端开发
1. 静态页面
2. 获取后端数据
3. 动态渲染
-->
</head>
<body>
<div class="container">
<!-- 动态渲染 -->
</div>
<script src="./js/index.js"></script>
</body>
详情页detail.html
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>商品详情</title>
</head>
<body>
<h2>商品详情</h2>
<div class="detail-wraper">
<!-- 动态渲染详情 -->
</div>
<script src="./js/detail.js"></script>
</body>
index.js
/**
* 获取商品列表数据
*/
function getProductList(){
//1.创建XMLHttpRequest对象
let xhr = new XMLHttpRequest()
//2. 建立连接
xhr.open('get','http://10.7.162.67:8888/goods/list')
//3.发送请求
xhr.send()
//4.接收响应数据
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status === 200){
let res = xhr.responseText
res = JSON.parse(res) // json格式字符串转json对象
console.log('res ',res)
showProductList(res.list)
}
}
}
}
/**
* 动态渲染商品列表
*/
function showProductList(productList){
let list = productList.map(item=>{
return `<div class="product-item" index="${item.goods_id}">
<img src="${item.img_big_logo}" alt="pic1">
<p>${item.title}</p>
<p>¥${item.price} ${item.goods_number}人已买</p>
<button index="${item.goods_id}">详情</button>
</div>`
})
const rootEle = document.querySelector('.container')
rootEle.innerHTML = list.join('')
rootEle.addEventListener('click',function(e){
e = e || window.event
let target = e.target || e.srcElement
let id = target.getAttribute('index')
console.log('id ',id);
// 跳转详情页
location.href = './detail.html?id='+id
})
}
getProductList()
detail.js
/**
* 获取商品id
* @returns
*/
function getProductId(){
let str = location.search// ?id=2
let id = str.split('=')[1]
return id
}
/**
* 获取商品详情
*/
function getProductDetail(){
let id = getProductId()
let xhr = new XMLHttpRequest()
xhr.open('get',`http://10.7.162.67:8888/goods/item?id=${id}`)
xhr.send()
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status === 200){
let res = xhr.responseText
res = JSON.parse(res)
if(res.code == 1){
let detail = res.info // 详情数据
showProductDetail(detail)
}
}
}
}
}
/**
* 动态渲染详情
*/
function showProductDetail(detail){
let str = `<img src="${detail.img_big_logo}" width="300" alt="">
<h2>${detail.title}</h2>
<p>商品数量${detail.goods_number}</p>
<p>¥${detail.price}</p>`
const detailWraper = document.querySelector('.detail-wraper')
detailWraper.innerHTML = str
}
getProductDetail()