前后端分离之form表单的提交

前后端分离之后,前后端基本呈现数据驱动的局面,后端组织数据发送给前端,前端整理数据传输给后端。

表单默认行为改变

原有的form表单会随着提交而跳转到另外一个页面,但是前后端分离之后,前端多是SPA页面,在不指定action时会提交到当前页面,指定action会跳转到其它页面,而无论哪一种操作,都会引发当前页面的刷新,导致数据提交失败。并且让后端再返回一个页面是一种不现实的操作,那么必须阻止表单的默认行为。

js提供了preventDefault方法来阻止表单的提交用法如下。

<form action="" onsubmit="submitUserInfo(event)" method="POST">
    <label for="username"></label>
    <input type="text" name="username">
    <button type="submit">提交</button>
</form>
<script>
    function submitUserInfo(e){
        e.preventDefault() //阻止表单提交
        console.log(e)
    }
</script>

表单数据读取

在前后端分离之前,不需要关系表单的读取,但是分离之后,采用ajax提交表单,此时很有必要知道,我们的表单包含了哪些数据。

在常见的MVVM框架中数据双向绑定来解决这个事情。例如vue可以在data当中设置表单的关联值,作为中间媒介。这样以来在视图和js代码中可以双向获取到该值。j

原生的js对表单提交也提供技术支持,formdata 接口就是js操作表单的数据的方式。

<form action="" onsubmit="submitUserInfo(event)" method="POST">
    <label for="username"></label>
    <input type="text" name="username">
    <button type="submit">提交</button>
</form>
<script>
    function submitUserInfo(e) {
        e.preventDefault()
        const formdata = new FormData(e.target)
        console.log(formdata.get("username"));
    }
</script>

如上所示,就是FormData获取表单值的方式。关于formdata的详尽用法可参考文档。https://developer.mozilla.org/zh-CN/docs/Web/API/FormData

关于请求头

原始的html表单提交,并不需要设置请求头,但是对于前后端分离之后,js代码并不能识别文件的内容形式,那么必须额外的告诉后端,我发送的是什么数据。

那么不得不在请求头指出文件格式:

formdata 特有的格式是:content-type : "multipart/form-data"

如果是json格式,得设置为:content-type : "content-type": "application/json"

那么前端程序员有必要了解各种类型

文件上传

情况一:

文件上传的方案比较多种多样了,比如刚刚从前后端分离过来,通常会把内容和文件一起发送给服务器。那么直接可在formData当中找到上传的文件,并且将formdata发送到服务器。

uploadToExcel() {
      const formData = new FormData();
      formData.append("file", this.currentUploadFile);
      formData.append(this.uploadType, this.uploadTypeValue);
      this.$axios
        .post(
          this.url,
          formData,
          {
            onUploadProgress: progressEvent => {
              this.process =
                ((progressEvent.loaded / progressEvent.total) * 100) | 0;
            }
          },
          { headers: { "Content-Type": "multipart/form-data" } }
        )
        .then(response => {
          let data = response.data;
          if (data.code !== 0) {
            this.$message.error("上传失败");
          } else {
            this.uploadFileList = [];
            this.currentUploadFile = null;
          }
        })
        .catch(error => {
          console.log("服务器故障");
        });
    },

浏览器数据请求如下

情况二:

可以在formdata中读出文件,并组织成json格式,服务器获取到文件字段,以二进制解析即可。

  • 8
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在前面的文章中,我们已经学习了如何使用DRF创建RESTful API,并将其与Angular应用程序集成。在本文中,我们将继续深入探讨如何使用DRF实现前后端分离。 ### 前后端分离 前后端分离是一种软件架构模式,其中前端和后端是独立的应用程序。前端应用程序通过API与后端应用程序通信,以获取数据并执行操作。这种模式有很多好处,例如: - 可以使前端和后端的开发人员专注于各自的任务,从而提高开发效率。 - 可以使前端和后端的技术栈不受限制,从而允许使用最佳的工具和技术。 - 可以使前端应用程序更容易扩展和重用。 ### 使用DRF实现前后端分离 我们可以使用DRF创建一个RESTful API,然后使用任何前端框架(如Angular、React或Vue.js)来消费它。在这里,我们将使用Angular作为前端框架。 #### 创建一个简单的Angular应用程序 我们首先需要创建一个基本的Angular应用程序。我们可以使用Angular CLI来创建一个新应用程序: ``` ng new my-app cd my-app ng serve ``` 现在我们可以在浏览器中访问`http://localhost:4200/`来查看我们的应用程序。 #### 使用HttpClient获取数据 接下来,我们需要使用Angular的HttpClient模块来获取数据。我们可以在Angular组件中注入HttpClient服务,并使用它来执行GET请求: ``` import { Component } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-root', template: ` <h1>Users</h1> <ul> <li *ngFor="let user of users">{{ user.username }}</li> </ul> `, }) export class AppComponent { users = []; constructor(private http: HttpClient) {} ngOnInit() { this.http.get('http://localhost:8000/api/users/').subscribe((data: any) => { this.users = data.results; }); } } ``` 在上面的代码中,我们使用`HttpClient`服务来执行GET请求,并将结果存储在`users`数组中。然后我们可以在HTML模板中使用`*ngFor`指令来遍历所有用户。 #### 使用HttpClient提交数据 我们也可以使用`HttpClient`服务来提交数据。例如,我们可以在Angular组件中创建一个新用户并将其提交到后端: ``` import { Component } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-root', template: ` <h1>New User</h1> <form (submit)="onSubmit()"> <label for="username">Username:</label> <input type="text" id="username" name="username" [(ngModel)]="username"> <br> <label for="email">Email:</label> <input type="email" id="email" name="email" [(ngModel)]="email"> <br> <button type="submit">Submit</button> </form> `, }) export class AppComponent { username = ''; email = ''; constructor(private http: HttpClient) {} onSubmit() { const data = { username: this.username, email: this.email }; this.http.post('http://localhost:8000/api/users/', data).subscribe((response: any) => { console.log(response); }); } } ``` 在上面的代码中,我们创建了一个表单来创建一个新用户。当用户提交表单时,我们使用`HttpClient`服务来执行POST请求,并将表单数据作为JSON对象传递给后端。 ### 结论 在本文中,我们学习了如何使用DRF和Angular创建一个前后端分离的Web应用程序。我们了解了如何使用Angular的HttpClient模块来获取和提交数据。我们还了解了前后端分离的好处,并了解了如何使用DRF实现这种模式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值