前端向后端传值的几种方式总结

一、HTML的标签form表单提交(常用)
from表单把所有属于表单中的内容提交给后台,例如输入框,单选框,多选框,文本域,文件域等。

  1. 在后台可通过对应的name属性获取相应的值。
  2. from表单中的action属性标识提交数据的地址。
  3. method属性指明表单提交的方式。

前端form表单:

在这里插入图片描述@RequestMapping("/index")     public String index(@RequestParam("username") String username,@RequestParam("password") String password){         System.out.println(username+"-"+password);         return "list.html";     }

 

 
测试请求:
http://localhost:10089/index?username=11&password=123

在这里插入图片描述$.ajax({             url: "/index",//后端地址             type: "post",      //提交方式             data: {                 //向后台提交的数据             },            dataType: "JSON",      //规定请求成功后返回的数据             success: function (data) {                 //请求成功之后进入该方法,data为成功后返回的数据             },            error: function (errorMsg) {                 //请求失败之后进入该方法,errorMsg为失败后返回的错误信息             }         });


总结:以上两种方式如果不显示的指定post提交方式,则默认的提交方式为get方式提交。此外,ajax中的url也可以直接通过字符串拼接,然后向后台提交数据,这种方式为get方式提交。下面详细说明

三、通过url字符串拼接向后台提交数据
1. 直接在ajax中url拼接数据

$.ajax({
            url: "/index?username="+username+"&password="+password,//后端地址(含参数)
            type: "get",      //提交方式
            dataType: "JSON",            error: function (errorMsg) {
                //请求失败之后进入该方法,errorMsg为失败后返回的错误信息
            }
        });


2. JS提交数据,通过window.location.href指定路径提交数据。

var deleteUser = function (deleteId) {
        if (confirm("确认删除编号是【"+deleteId+"】的成员吗?")){
            window.location.href="/DeleteUserServlet?deleteId="+deleteId;  //后端地址(含参数)
        }
    }


3. 通过a标签提交数据,通过a标签的href属性提交数据,和js提交数据类似。

<a href="/index?username="+username+"&password="+password"></a>


四、 后端返回前端数据
后端数据放到org.springframework.ui.model中,前端HTML就能直接在取出来

后端代码:
使用Model的addAttribute方法,将数据放到model中   

@RequestMapping("/index")
    public String index(
            @RequestParam("username") String username,            @RequestParam("password") String password,            //将查询到的数据通过org.springframework.ui.Model
            Model model) {
        Person person = personService.login(username,password);
        System.out.println(username + "-" + password);
        if (person != null) {
            return "list.html";
        } else {
            //将错误信息提示前端
            model.addAttribute("msg","账号密码不正确");
            return "index";
        }
    }

前端代码:
thymeleaf使用${}获取后端数据,

    <!--/*@thymesVar id="msg" type=""*/-->
    <p th:text="${msg}" style="color: red" ></p>

相关文章

$.AJAX()方法中的PROCESSDATA参数 在使用jQuery的$.ajax()方...
form表单提交的几种方式 表单提交方式一:直接利用form表单提...
文章浏览阅读1.3k次。AJAX的无刷新机制使得在注册系统中对于...
文章浏览阅读1.2k次。 本文将解释如何使用AJAX和JSON分析器在...
文章浏览阅读2.2k次。/************************** 创建XML...
文章浏览阅读3.7k次。在ajax应用中,通常一个页面要同时发送...