fetch()方法是用来替代原来的ajax方法的,据说用的Promise,但是这个我不太懂,只能记录几个常用例子。
fetch('a.php?name=nciaer&age=18').then(res => {
if(res.ok && res.status == 200) { // 如果请求正确,那么ok=true,status是返回的状态码,正常应该是200
return res.json(); // 返回内容解析成json格式
// return res.text(); // 返回内容解析成文本模式
}
}).then(data => { // 这里可以直接使用返回的数据
console.log(data)
});
fetch('a.php', {
method: 'post', // 这里设置post请求
headers: {
'Content-Type': 'application/x-www-form-urlencoded' // 设置Content-Type
},
body: 'name=nciaer' // post数据
}).then(res => {
if(res.status == 200 && res.ok) {
return res.text()
}
}).then(data => {
console.log(data)
})
post请求必须设置Content-Type,否则后端($_POST)接收不到,如果不设置Content-Type,那么默认的是text/plain。
似乎实际中,更多的是发送json数据,如下面这个例子:
let data = {name: 'nciaer'};
fetch('a.php', {
method: 'post', // 这里设置post请求
headers: {
'Content-Type': 'application/json' // 设置Content-Type
},
body: JSON.stringify(data) // data转成json
}).then(res => {
if(res.status == 200 && res.ok) {
return res.text()
}
}).then(data => {
console.log(data)
})
后端就不能用$_POST来获取了,需要用file_get_contents('php://input')
来获取json数据。
根据这两天学习的,再补充下。
如果第一个then里res的status状态码是2xx,那么ok就是true,否则就是false。
为什么需要两个then?难道一个不行吗?因为第一个then回调函数里返回的是Respone对象,数据还得进一步处理才能使用,并且res调用text()或者json()方法返回的还是一个Promise,所以继续用then链式调用。