1 , fetch,请求本地json文件
//GET请求
<button>点击获取</button>
<script>
var btn = document.querySelector('button')
btn.onclick = function(){
fetch('list.json') //请求地址
.then(res=>res.json()) //将请求到的数据转换为json js对象
.then(res=>{ //输出数据
console.log(res)
})
}
</script>
2, fetch,POST请求
//POST上传请求
<button>点击</button>
<script>
var btn = document.querySelector('button')
btn.onclick = function(){
fetch('https://www.XXX.com/ajax/echo.php',{ //请求的服务器地址
body:"name=mumu&&age=20", //请求的数据
// body:{name:"mumu",age:20}, //第二种请求数据的方法json
method:"POST", //请求方法
headers:{ //请求头信息
'Content-Type':'application/x-www-form-urlencoded' //用url编码形式处理数据
// 'Content-Type':'application/json' //第二种请求头编写方式json
}
})
.then(res=>res.text()) //请求得到的数据转换为text
.then(res=>{
console.log(res) //打印输出
})
.catch(err=>{ //错误打印
console.log(err)
})
}
</script>
3 解决跨域
fetch('http://localhost:3000', {
mode: 'no-cors'
}).then(res => {
console.log('response', res)
return res.text()
}).then(body => {
console.log('body', body)
})