一、背景
在我们的项目开发过程中我们需要向后端发送请求,实现前后端的数据交互,我们可以使用的方法有在路由中有以下的几种方式:
- 在URL的请求路径中增添参数
- 使用url+参数的方式完成数据的请求
- 使用ajax
- 使用form的方法
二、比较
我们对上面的几种方法进行比较
方法 | 形式 | 优势 |
---|---|---|
url路由带参数 | /student/{id} | 简单、便捷 |
url+参数 | @{href="{/student/(value=${object.x})}"} | 可以简单实现多参数的传递 |
ajax | $(‘ajax’){…} | 可以传递多种复杂的数据类型 |
form | <form action="{target}" type=""> …</form> | 可以直接将填写的数据发送 |
三、实现
3.1 url路由带参数
<a href="#" th:href="@{/admin/news/{id}/toUpdate(id=${news.id})}" class="ui mini teal basic button">编辑</a>
3.2 url+参数
<a href="#" th:href="@{/student/chooseClassLogic(studentId=${course.studentId},courseId=${course.courseId},startTime=${course.startTime},endTime=${course.endTime})}" class="ui positive button">添加</a>
3.3 ajax方式
$.ajax({
type : 'post',
url: "/student/changePassword",
data: {repassword, password},
success: function (res) {
alert(res.message)
$(location).attr('href', '/student/profile')
},
error: function (err) {
alert('更新用户失败')
}
})
3.4 form表单
<form action="/student/loginJudge" method="get">
<input type="text" value="" placeholder="用户名" name="name" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'User name';}"/>
<input type="password" value="" placeholder="密码" name="password" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'password';}"/>
<div class="remember">
<span class="checkbox1">
<label class="checkbox"><input type="checkbox" name="" checked=""><i> </i>记住我 </label>
</span>
<div class="forgot">
<h6><a href="#">忘记密码</a></h6>
</div>
<div class="clear"></div>
</div>
<input type="submit" value="Login">
</form>
四、总结
上述列举了一些后端数据发送请求的方式过程,基本上很多的开发模式都是这样实现,因此也可以扩展到其他的web模式开发中。