前端程序获取后台数据小案例

74 阅读1分钟

1html页面

DPlayeeweer.png

DPlayeeeer.png

2css样式

*{padding: 0;margin: 0;}
.container{
    width: 1200px;
    margin: 100px auto;
    display: flex;
    //让所有块处于同一行
    //换行,每排4个
    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%;
}

通过js文件获取后端数据

使用ajax
/**
 * 获取商品列表数据
 */
function getProductList(){
    //1.创建XMLHttpRequest对象
    let xhr = new XMLHttpRequest()
    //2. 建立连接
    xhr.open('get','http://本机IP地址: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=>{
        // 通过模板字符串+map方法遍历动态获取后端数据
        return `<div class="product-item">
                    <img src="${item.img_big_logo}" alt="pic1">
                    <p>${item.title}</p>
                    <p>¥${item.price}  ${item.goods_number}人已买</p>
                </div>`
    })
    const rootEle = document.querySelector('.container')
    // map方法返回的是数组,此处通过join方法将数组转化为字符串并追加到rootEle元素下面
    rootEle.innerHTML = list.join('')
}

getProductList()