今天给大家讲解两种让页面建立联系的方式
一、重定向
二、表单提交
先看第一种方式,重定向
首先需要了解客户端发起请求的过程
1、客户端向服务端发起请求,比如请求地址是:http://127.0.0.1:8000/lili/submit/
2、程序根据路由找到视图函数
3、执行视图函数,比如视图函数是要求打开submit.html
4、操作视图函数返回的html中的按钮,点击页面中 的按钮,如图
5、调用这个按钮绑定的方法,重点来了
在方法中这样写:
window.location.href = 'http://127.0.0.1:8000/lili/result/'
查看图片:
6、加载新的代码,然后重新访问:http://127.0.0.1:8000/lili/submit/
7、点击submit这个按钮,这样就跳转成功了
二、表单提交
1、创建模型,代码如下
from django.db import models
from django.contrib.auth.models import Userclass Feedback(models.Model):quality = models.IntegerField('商品质量', default=1)attitude = models.IntegerField('客服态度', default=1)speed = models.IntegerField('物流速度', default=1)text = models.TextField('评论内容', max_length=150, default='')anonymous = models.BooleanField('是否匿名', default=True)created_at = models.DateTimeField(auto_now_add=True)updated_at = models.DateTimeField(auto_now=True)name: str = "lili"objects: models.QuerySet # 普通的属性
2、生成迁移脚本:
python .\manage.py makemigrations
python .\manage.py migrate
3、编辑views.py,编写视频函数,代码如下
import json
import osfrom django.contrib.auth import login, logout
from django.shortcuts import render
from django.http import JsonResponse, HttpResponse, HttpResponseRedirect, HttpResponsePermanentRedirect
from django.contrib.auth.models import User
from django.contrib.auth.hashers import make_password
from django.template.loader import render_to_string
from django.urls import reversefrom lili.models import Feedbackdef submit(request):if request.method == 'GET':html = open("submit.html", encoding="utf-8").read()return HttpResponse(html)elif request.method == 'POST':# 获取提交的表单数据data = json.loads(request.body)print(data)obj = Feedback()obj.quality = data.get('quality', 0)obj.attitude = data.get('attitude', 0)obj.speed = data.get('speed', 0)obj.text = data.get('text', '')obj.anonymous = data.get('anonymous', False)obj.save()request.session['feedback_data'] = datareturn JsonResponse({'status': 'success'})def result(request):html = open("result.html",encoding="utf-8").read()return HttpResponse(html)def submit_5524(request):if request.method == 'POST':data = json.loads(request.body)print(data)return JsonResponse({'status': 'success','data':data})html = open("submit.html",encoding="utf-8").read()return HttpResponse(html)
4、编辑html文件,通过这个文件实现先后端的交互,比如点击操作,以下是submit.py的示例代码
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" /><title>VForm Demo</title><link rel="stylesheet" href="https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/element-plus/2.0.4/index.min.css" /><link rel="stylesheet" href="https://ks3-cn-beijing.ksyun.com/vform3/render.style.css?t=20220129"><style type="text/css"></style>
</head>
<body><div id="app"><v-form-render :form-json="formJson" :form-data="formData" :option-data="optionData" ref="vFormRef"></v-form-render><el-button type="primary" @click="submitForm">Submit</el-button></div><script src="https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/vue/3.2.30/vue.global.min.js"></script>
<script src="https://lf9-cdn-tos.bytecdntp.com/cdn/expire-1-M/element-plus/2.0.4/index.full.min.js"></script>
<script src="https://ks3-cn-beijing.ksyun.com/vform3/render.umd.js?t=20220129"></script>
<script>const { createApp } = Vue;const app = createApp({data() {return {formJson: {"widgetList":[{"key":40214,"type":"rate","icon":"rate-field","formItemFlag":true,"options":{"name":"quality","label":"商品质量","labelAlign":"","defaultValue":null,"columnWidth":"200px","labelWidth":null,"labelHidden":false,"disabled":false,"hidden":false,"required":false,"requiredHint":"","validation":"","validationHint":"","customClass":[],"labelIconClass":null,"labelIconPosition":"rear","labelTooltip":null,"max":5,"lowThreshold":2,"highThreshold":4,"allowHalf":false,"showText":false,"showScore":false,"onCreated":"","onMounted":"","onChange":"","onValidate":""},"id":"rate73475"},{"key":40214,"type":"rate","icon":"rate-field","formItemFlag":true,"options":{"name":"attitude","label":"客服态度","labelAlign":"","defaultValue":null,"columnWidth":"200px","labelWidth":null,"labelHidden":false,"disabled":false,"hidden":false,"required":false,"requiredHint":"","validation":"","validationHint":"","customClass":"","labelIconClass":null,"labelIconPosition":"rear","labelTooltip":null,"max":5,"lowThreshold":2,"highThreshold":4,"allowHalf":false,"showText":false,"showScore":false,"onCreated":"","onMounted":"","onChange":"","onValidate":""},"id":"rate59589"},{"key":40214,"type":"rate","icon":"rate-field","formItemFlag":true,"options":{"name":"speed","label":"物流速度","labelAlign":"","defaultValue":null,"columnWidth":"200px","labelWidth":null,"labelHidden":false,"disabled":false,"hidden":false,"required":false,"requiredHint":"","validation":"","validationHint":"","customClass":"","labelIconClass":null,"labelIconPosition":"rear","labelTooltip":null,"max":5,"lowThreshold":2,"highThreshold":4,"allowHalf":false,"showText":false,"showScore":false,"onCreated":"","onMounted":"","onChange":"","onValidate":""},"id":"rate28142"},{"key":116462,"type":"input","icon":"text-field","formItemFlag":true,"options":{"name":"text","label":"评论","labelAlign":"","type":"text","defaultValue":"","placeholder":"","columnWidth":"200px","size":"","labelWidth":null,"labelHidden":false,"readonly":false,"disabled":false,"hidden":false,"clearable":true,"showPassword":false,"required":false,"requiredHint":"","validation":"","validationHint":"","customClass":"","labelIconClass":null,"labelIconPosition":"rear","labelTooltip":null,"minLength":null,"maxLength":null,"showWordLimit":false,"prefixIcon":"","suffixIcon":"","appendButton":false,"appendButtonDisabled":false,"buttonIcon":"custom-search","onCreated":"","onMounted":"","onInput":"","onChange":"","onFocus":"","onBlur":"","onValidate":"","onAppendButtonClick":""},"id":"input110400"},{"key":25114,"type":"switch","icon":"switch-field","formItemFlag":true,"options":{"name":"anonymous","label":"是否匿名","labelAlign":"","defaultValue":false,"columnWidth":"200px","labelWidth":null,"labelHidden":false,"disabled":false,"hidden":false,"customClass":"","labelIconClass":null,"labelIconPosition":"rear","labelTooltip":null,"switchWidth":40,"activeText":"","inactiveText":"","activeColor":null,"inactiveColor":null,"onCreated":"","onMounted":"","onChange":"","onValidate":""},"id":"switch99841"}],"formConfig":{"modelName":"formData","refName":"vForm","rulesName":"rules","labelWidth":80,"labelPosition":"left","size":"","labelAlign":"label-left-align","cssCode":"","customClass":[],"functions":"","layoutType":"PC","jsonVersion":3,"onFormCreated":"","onFormMounted":"","onFormDataChange":""}},formData: {},optionData: {}}},methods: {submitForm() {this.$refs.vFormRef.getFormData().then( (formData) => {// Form Validation OK// alert( JSON.stringify(formData) )fetch('/lili/submit/',{method: 'POST',headers:{'Content-Type': 'application/json'},body: JSON.stringify(formData)}).then(data => {// document.open();// document.write(data.html);// document.close();window.location.href ='http://127.0.0.1:8000/lili/result/'})}).catch( function(error) {// Form Validation Failedalert(error)})}}});app.use(ElementPlus)app.use(VFormRender)app.mount("#app");
</script>
</body>
</html>
持续不断的总结输出,一定可以厚积薄发,如果觉得我的文章有帮助到你,望你关注,笔芯