<!DOCTYPE html>
<html lang="en">
<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>Document</title>
</head>
<body>
<h2>ajax parse json data</h2>
<h2>Recommended works of Imaden Pearl</h2>
<button>Click to parse data</button>
<!-- <link rel="stylesheet" href="./data/"> -->
<ul>
<!-- <li>
<p>Book title: Love in the Time of Cholera</p >
<p>Author: Marquez</p >
</li> -->
</ul>
<script>
// The effect: click the button, send an ajax request to the backend, process it and render it to the page.
const ul = document.querySelector('ul')
document.querySelector('button').onclick = function(){
// 1. Creating objects
let xhr = new XMLHttpRequest();
// 2. Open
xhr.open('post','./data/','true')
// 3. Send the request
xhr.send()
// 4. Listening and Handling
xhr.onreadystatechange = function(){
if(xhr.readyState===4 && xhr.status===200){
// Start processing real data
// Process: return data, convert string to js object, render to page
let str = xhr.response;
// (str);
// Convert a json string to a js object.
let obj = JSON.parse(str)
// (obj);
// Get the data array inside the js object.
let dataArr = obj.data
// (dataArr);
// Render the objects in the array into ul (create li, append to ul).
// Rendering 1
// for(let i = 0;i<;i++){
// let lis= ('li')
// = `
// <p> Book name: ${dataArr[i].name}</p >
// <p> Author: ${dataArr[i].author}</p >
// <p> description: ${dataArr[i].desc}</p >
// `
// (lis)
// Rendering 2
let strli = ''
for(let i = 0;i<dataArr.length;i++){
strli += `<li>
<p> Book Title:${dataArr[i].name}</p >
<p> Author:${dataArr[i].author}</p >
<p> Description:${dataArr[i].desc}</p >
</li>
`
console.log(strli);
}
ul.innerHTML = strli
}
}
}
</script>
</body>
</html>