实例演示fetch , async, await 的用法
html
<!DOCTYPE html>
<html lang="zh-CN">
<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>
<button onclick="getData(this)">test</button>
<div class="list">
</div>
<script>
async function getData(eee){
const ad = document.querySelector('.list')
const response= await fetch(`{:U('Home/Index/ve')}`)
console.log(response);
const result = await response.json()
console.log(result.length)
let htm = '<ul>'
for(i=0 ;i<result.length; i++){
htm += `<li>${result[i].title}</li>`
}
htm +='</ul>'
console.log(htm)
ad.insertAdjacentHTML("beforeend",htm)
}
PHP
public function ve(){
$arr = array(
array('id'=>1,'title'=>'小花'),
array('id'=>2,'title'=>'小mi'),
array('id'=>3,'title'=>'小qi')
);
echo json_encode($arr);
}
效果