一、通过json前后交互字符串。这是最常用的
前提:fetch前后端交互字符串,必须通过json传递
1.在cshtml里,添加如下内容,具体见注释
<script>
function PressEvent() {
fetch('/home/FetchTest', { //绑定controller里的函数(用链接亦可)
method: 'POST', //用post形式
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ param1: 'qwer' }) //把需要传给后端的内容,做成json
})
.then(response => response.json()) //先返回response,用json处理一下,即可在下一步里直接处理data
.then(data => {
alert(data); //处理从后端返回来的data
})
.catch(error => alert(error)); //协助定位问题
}
</script>
<button onclick="PressEvent()">点击</button> //添加一个按钮,绑定fetch()
2.在后端写个类,定义从前端接收的数据格式:
public class Test1 //与第一步里body中的json相互呼应
{
public string param1 { get; set; }
}
3.在controller里添加处理数据的方法
[HttpPost] //不可少
public IActionResult FetchTest([FromBody]Test1 test1) //用刚刚定义好类声明参数,并说明从body里获取数据
{
if (test1.param1 == "qwer") //处理数据
{
return Json("asdf"); //以json的形式,把字符串传给前端
}
else
{
return Json("zxcv");
}
}
二、fetch可以传递多种类型的数据,未完待续。。。。。。
1万+

被折叠的 条评论
为什么被折叠?



