前后端分离初探2

89 阅读1分钟

动态渲染出商品列表

  function showProductList(productList) {
            let str = `<tr>
                  <th>商品名称</th>
                  <th>商品图片</th>
                  <th>商品价格</th>
                  <th>商品数量</th>
                  <th>操作 </th>
                </tr>`
            // 遍历商品数组
            //使用map方法遍历商品列表,返回一个新数组
            let trArray = productList.map(item => {
                return `<tr>
                      <td>${item.name}</td>
                      //控制宽度
                      <td><img src="${item.url}" width="100" alt="pic"/></td>
                      <td>${item.price}</td>
                      <td>${item.num}</td>
                      <td>删除</td>
                    </tr>`
            })
            //将数组转换成字符串
            str = str + trArray.join('')
            //用table接收新字符串
            table.innerHTML = str
        }

完整代码

后端

let http = require('http') // 引入内置http模块
// 创建一个web服务
let server = http.createServer(function (request, response) {
	// request 请求对象
	// response 响应对象
	// 跨域问题
	response.setHeader('Access-Control-Allow-Origin','*')
	// 解决乱码
	response.writeHead(200, { 'content-type': 'text/html;charset=utf-8' })
	// 商品列表
	let productList = [
		{
			number: 1001,
			name: 'javascript高级编程',
			url: 'https://img2.baidu.com/it/u=1814268193,3619863984&fm=253&fmt=auto&app=138&f=JPEG?w=632&h=500',
			price: 88.98,
			num: 0,
			state: false,
		},
		{ number: 1002, name: 'css高级编程', url: 'https://img1.baidu.com/it/u=3217543765,3223180824&fm=253&fmt=auto&app=120&f=JPEG?w=1200&h=750', price: 58.58, num: 0, state: false },
		{ number: 1003, name: 'html高级编程', url: 'https://img2.baidu.com/it/u=2983827435,378917087&fm=253&fmt=auto&app=138&f=JPEG?w=374&h=500', price: 48.58, num: 0, state: false },
	]
  productList = JSON.stringify(productList)

	// let loginPage = `
	//   <form>
	//     <p>登录界面</p>
	//     <input type="text" /><br>
	//     <input type="password" /><br>
	//     <input type="submit"/>
	//   </form>
	// `
	response.write(productList) // 向响应对象写入数据helloworld
	response.end() // 结束写入,发送数据给请求客户端
})

// 启动web服务, 端口号   http://10.7.162.67:3000  3000端口号, 作用: 区分同一台电脑中不同应用
server.listen(3000, () => console.log('web服务启动成功,监听3000端口...'))

前端

<body>
    <button class="product-list">获取商品列表数据</button>
    <p></p>
    <table>
        <!-- 动态渲染 -->
    </table>
    <script>
        const btn = document.querySelector('.product-list')
        const pEle = document.querySelector('p')
        const table = document.querySelector('table')
        btn.addEventListener('click', function () { })

        getProductList()
        /**
         *异步获取后端商品列表数据
         */
        function getProductList() {
            // 1. 创建XMLHttpRequest
            let xhr = new XMLHttpRequest()
            // 2. 建立连接
            xhr.open('get', 'http://10.7.162.138:3000')
            // 3. 发送请求
            xhr.send()
            // 4. 接收响应数据
            xhr.onreadystatechange = function () {
                // 4.1 是否响应完成
                if (xhr.readyState === 4) {
                    // 4.2 是否成功响应
                    if (xhr.status === 200) {
                        let data = xhr.responseText // 响应内容
                        let dataObj = JSON.parse(data)
                        showProductList(dataObj)
                    } else {
                        alert('网络出错 ' + xhr.status)
                    }
                }
            }
        }
        /*
        商品列表渲染
        */
        function showProductList(productList) {
            let str = `<tr>
                  <th>商品名称</th>
                  <th>商品图片</th>
                  <th>商品价格</th>
                  <th>商品数量</th>
                  <th>操作 </th>
                </tr>`
            // 遍历商品数组
            let trArray = productList.map(item => {
                return `<tr>
                      <td>${item.name}</td>
                      <td><img src="${item.url}" width="100" alt="pic"/></td>
                      <td>${item.price}</td>
                      <td>${item.num}</td>
                      <td>删除</td>
                    </tr>`
            })
            str = str + trArray.join('')
            table.innerHTML = str
        }
    </script>
</body>