Ajax请求(页面不革新)
依赖JQuery
Ajax基本代码代码
- {% block js %}
- <script type="text/javascript">
- $(function(){
- //页面框架加载完成之后代码自动执行
- bindBtnEvent();
- })
- function bindBtnEvent(){
- $("#btn1").click(function(){
- $.ajax({
- url:'/task/ajax/',
- type:"get",
- data:{
- n1:123,
- n2:456
- },
- dataType:"JSON",
- success:function(res){
- console.log(res);
- console.log(res.status);
- console.log(res.data);
- }
- })
- })
- }
- </script>
- {% endblock %}
-
复制代码 url.py编写——他返回的是一个json数据
- #任务管理
- path('task/list/',views.task_list),
- #
- path('task/ajax/',views.task_ajax),
- path('task/add/',views.task_add),
-
复制代码 view.py编写
- #导入
- # from app01 import models
- # from app01.utils.bootstrap import BootStrapModelForm
- from django import forms
- class TaskModelForm(BootStrapModelForm):
- class Meta:
- model =models.Task
- fields ="__all__"
- widgets ={
- "detail":forms.TextInput
- }
- #任务列表
- def task_list(request):
-
- #实例化
- form =TaskModelForm
- return render(request,"task_list.html",{"form":form})
- #导入
- from django.views.decorators.csrf import csrf_exempt
- import json
- from django.http import JsonResponse
- # @csrf_exempt
- def task_ajax(request):
- print(request.GET)
- data_dict = {"status":True,'data':[11,22,33,44]}
- json_string = json.dumps(data_dict)
- return HttpResponse(json_string)
- #return JsonResponse(data_dict)
- @csrf_exempt
- def task_add(request):
- #< QueryDict: {'level': ['1'], 'title': ['标题'], 'detail': ['详细信息'], 'user': ['2']} >
- # print(request.POST)
-
- #用户发送过来的数据进行校验(modelForm进行校验)
- form = TaskModelForm(data=request.POST)
- if form.is_valid():
- form.save()
- data_dict = {"status": True}
- return HttpResponse(JsonResponse(data_dict))
- data_dict ={"status":False,"error":form.errors}
- return HttpResponse(json.dumps(data_dict,ensure_ascii=False))
复制代码 在HTML中编写
- {% extends 'layout.html'%}
- {% block content %}
- <div class="container">
- <div class="panel panel-default">
- <div class="panel-heading">新建任务表单</div>
- <div class="panel-body">
- <form id="formAdd">
- <div class="clearfix">
- {% for field in form %}
- <div class="col-xs-6">
- <div class="form-group" style="position:relative; margin-bottom:20px;">
- <label >{{ field.label }}</label>
- {{ field }}
- <span class="error-msg" style="color:red; position: absolute;"></span>
- </div>
- </div>
- {% endfor %}
- <div class="col-xs-6">
- <button id="btnAdd" type="button" class="btn btn-primary">提 交</button>
- </div>
- </div>
- </form>
- </div>
- </div>
- <hr/>
- <h1>Ajax学习</h1>
- <h3>示例1</h3>
- <input id="btn1" type="button" class="btn btn-primary" value="点击1" onclick="clickMe();">
- <h3>示例2</h3>
- <input id="txtUser" type="text" placeholder="姓名">
- <input id="txtAge" type="text" placeholder="年龄">
- <input id="btn2" type="button" class="btn btn-primary" value="点击2" onclick="clickMe();">
- <h3>示例3</h3>
- <form id="form3">
- <input name="user" type="text" placeholder="姓名">
- <input name="age" type="text" placeholder="年龄">
- <input name="email" type="text" placeholder="邮箱">
- <input name="more" type="text" placeholder="介绍">
- <input id="btn3" type="button" class="btn btn-primary" value="点击3" >
- </form>
- </div>
- {% endblock %}
- {% block js %}
- <script type="text/javascript">
- $(function(){
- //页面框架加载完成之后代码自动执行
- bindBtnEvent();
- bindBtnEvent2();
- bindBtnEvent3();
- bindBtnAddEvent();
- })
- function bindBtnEvent(){
- $("#btn1").click(function(){
- $.ajax({
- url:'/task/ajax/',
- type:"get",
- data:{
- n1:123,
- n2:456
- },
- dataType:"JSON",
- success:function(res){
- console.log(res);
- console.log(res.status);
- console.log(res.data);
- }
- })
- })
- }
- function bindBtnEvent2(){
- $("#btn2").click(function(){
- $.ajax({
- url:'/task/ajax/',
- type:"get",
- data: {
- name:$("#txtUser").val(),
- age:$("#txtAge").val()
- },
- dataType:"JSON",
- success:function(res){
- console.log(res);
- console.log(res.status);
- console.log(res.data);
- }
- })
- })
- }
- function bindBtnEvent3(){
- $("#btn3").click(function(){
- $.ajax({
- url:'/task/ajax/',
- type:"get",
- data:$("#form3").serialize(),
- dataType:"JSON",
- success:function(res){
- console.log(res);
- console.log(res.status);
- console.log(res.data);
- }
- })
- })
- }
- function bindBtnEvent3(){
- $("#btnAdd").click(function(){
- $(".error-msg").empty();
- $.ajax({
- url:'/task/add/',
- type:"post",
- data:$("#formAdd").serialize(),
- dataType:"JSON",
- success:function(res){
- if(res.status){
- alert("添加成功!")
- } else {
- $.each(res.error,function(name,data){
- $("#id_"+ name).next().text(data[0]);
- }
- )
- }
- }
- })
- })
- }
- </script>
- {% endblock %}
复制代码 在model.py中编写
- #任务表
- class Task(models.Model):
- level_choices ={
- (1,"紧急"),
- (2,"重要"),
- (3,"临时"),
- }
- level = models.SmallIntegerField(verbose_name="级别",choices=level_choices,default=1)
- title = models.CharField(verbose_name="标题",max_length=64)
- detail = models.TextField(verbose_name="详细信息")
-
- user = models.ForeignKey(verbose_name="负责人",to="Admin",on_delete=models.CASCADE)
复制代码 终极显示样式
为了是管理员表显示name而不是对象
- #输出显示函数——不输出对象
- def __str__(self):
- return self.username
复制代码 注:为了节约时间不像之前那样详细,之后偶然间复习我会重新编辑。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |