[AJAX]使用fetch发送请求
warning:
这篇文章距离上次修改已过431天,其中的内容可能已经有所变动。
在JavaScript中,可以使用fetch函数来发送AJAX请求。以下是一个使用fetch发送GET和POST请求的例子:
GET请求示例:
fetch('https://api.example.com/data', {
method: 'GET',
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));POST请求示例:
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ key: 'value' })
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));在这些例子中,我们使用了fetch函数,它返回一个promise对象。然后我们使用.then()来处理响应,将其转换为JSON(如果可能的话),并在控制台中打印出来。如果在请求过程中出现错误,我们使用.catch()来捕获错误并在控制台中输出。
评论已关闭