1、提交JSON格式的数据
Ajax发起请求:
async function test_fetch_post( params ){
try{
let res = await fetch('/demo_ajax/ajax/test_fetch_post',{
method: 'POST',
headers:{
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify(params)
});
return await res.json();
}catch (err){
console.warn(err);
}
}
后端接收数据:
public function test_fetch_post( Request $request ){
$params = $request->getContent();//必须使用getContent()方法才能取到值。
$user = json_decode($params, TRUE);//将json字符串转成数组
//其他代码...
}
2、提交表单数据
Ajax发起请求:
fetch('/demo_ajax/ajax/endpoint_1', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'X-CSRF-Token': token,
},
body: 'key1=value1&key2=value2',
})
.then(response => response.json())
.then(result => console.log(result.data.key1))
.catch(error => console.error('Error:', error));
后端接收数据:
public function endpoint1( Request $request ) {
$params = $request->request->all();//获取请求的参数
// 处理 AJAX 请求并返回响应
}