Django下的ajax加法运算框实现
本博文源于django基础,主要对django中前后端互传数据进行测试和学习。ajax八字核心“局部刷新,异步传输”。因此我们可以用jquery作为前端接受,jquery发送到django中,django进行处理好,再返回出去。jquery做最后的显示工作。
·
本博文源于django基础,主要对django中前后端互传数据进行测试和学习。ajax八字核心“局部刷新,异步传输”。因此我们可以用jquery作为前端接受,jquery发送到django中,django进行处理好,再返回出去。jquery做最后的显示工作。因此实验步骤如下:
实验步骤
假设项目名称test01,应用名称app01,页面名称为index.html
- 在test01/urls.py配置路由
- 在app01/views.py下书写render函数跳转html
- 在templates/index.html书写布局及jquery中ajax操作
- 转到app01/views.py书写处理函数,以及输出信息
- 实验测试,收获喜悦!
实验细节代码
test01/urls.py下配置路由
from django.contrib import admin
from django.urls import path
from app01 import views # 新增
urlpatterns = [
path('',views.ab_ajax), # 新增
path('admin/', admin.site.urls),
]
app01/views.py书写render函数
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
from django.views import View
def ab_ajax(request):
return render(request,'index.html')
templates/index.html写界面和ajax操作
jquery文件路径一定会配置!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index</title>
<script src="/static/plugins/js/jquery-3.5.1.min.js"></script>
</head>
<body>
<input type="text" id="d1">+
<input type="text" id ='d2'>=
<input type="text" id ='d3'>
<p>
<button id="btn">点我</button>
</p>
<script>
$('#btn').click(function(){
//朝后端发送ajax请求
$.ajax({
//1.指定哪个后端发送ajax请求
url:'',//不写就是当前地址提交
type:'post',//2.请求方式,不指定默认get
//3.数据
// data:{'username':'jason','password':123},
data:{'i1':$('#d1').val(),'i2':$('#d2').val()},
//4.回调函数
success:function(args){
$('#d3').val(args)
}
})
})
</script>
</body>
</html>
将app01/views.py书写完整加上业务处理
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
from django.views import View
def ab_ajax(request):
if request.method == 'POST':
i1 = request.POST.get('i1')
i2 = request.POST.get('i2')
# 先转成整形再加
i3 = int(i1) + int(i2)
print(i3)
return HttpResponse(i3)
return render(request,'index.html')
实验测试,收获喜悦
希望博文能对大家有所帮助,如果大家对这个不是很理解,可参考此博文,教大家settings.py一般配置并跑通helloworld
django从零基础配置settings.py

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐
所有评论(0)