html+ajax+django简单测试(前后端分离)

html+ajax+django+前后端分离

1.基本写法

这里使用jq的ajax
可以参考菜鸟教程和菜鸟工具
$.ajax({
url:‘’, //接口地址
type:‘’, //默认是get;这是请求方式
header:{},
dataType:“”,//设置接受到的响应数据的格式
data:‘’ //给后端的数据 json类型
success:function(res){
//请求成功的函数 httpstatuscode=200,这里函数可以function命名单独拿出来写
},
error:function(e){
//请求失败后的函数 httpstatuscode!=200
}
})

url说明:
相对路径
//url 以根路径开头(/)的请求路径,表示该路径是基于服务器的根路径的,则请求地址为服务器路径+url,
//在本地开发的时候,一般http://localhost:port是作为服务器路径的
//不以根路径开头,表示该路径是基于当前html路径的,请求地址为页面地址+url
绝对路径
var baseurl=“http://ip+port/”;//ajax请求地址头部,服务器路径
url:baseurl+“相对路径”

2.ajax与html,django的交互

模拟前后端分离(不完全的)
django创建一个项目,前端后端部署在同一个django服务里,其实没有分离,只是写法上分离了(注意分离不能用模板标签)
*

2.1#前端

2.1.1页面

test.html:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ajax测试</title>
</head>
<body>
<div>
    <button onclick="fun1()">get请求无参数</button>
    <div id="test">index</div>
    <div id="test2">index</div>
</div>
<br/>
<div>
    <button onclick="fun2()">get请求带参数</button>
    <div id="test3">index2</div>
    <div id="test4">index2</div>
</div>
<br/>

<div>
    <button onclick="fun3()">post请求无参数</button>
    <div id="test5">index3</div>
    <div id="test6">index3</div>
</div>
<br/>
<div>
    <button onclick="fun4()">post请求无参数</button>
    <div id="test7">index4</div>
    <div id="test8">index4</div>
</div>

<br/>
<div>
    <label for="name">名字</label>
    <input type="text" id="name" name="name">

    <label for="age">年龄</label>
    <input type="text" id="age" name="age">
    <button type="submit" onclick="submit1()">提交</button>
    <div id="test9">index5</div>
</div>
<br/>

<div>
    <label for="name">id</label>
    <input type="text" id="id" name="id">

    <label for="sex">性别</label>
    <input type="text" id="sex" name="sex">
    <button type="submit" onclick="submit2()">提交</button>
    <div id="test10">index6</div>
</div>



</body>

<script src="https://cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/bootstrap/4.6.0/js/bootstrap.min.js"></script>
<script>
//可以写fuction 给绑定触发,把ajax放进去;如果不放入function触发,直接刷新get访问index页面即可自动执行ajax

//get不传参方式的ajax
function fun1() {
    $.ajax({
    url:"/indexApi",  //对应后端接口 如果后端接口/结尾,这里没有/结尾,网络里除了200会多个301,故这里建议都不带
    type:"get",
    success:function (res) {
        //json格式在前端是object类型
        console.log(res) //res代表后端接口的jsonresponse
        console.log(typeof(res)) //在console打印数据类型
        $("#test").text(JSON.stringify(res)) //object转字符串
        $("#test2").text(res.data)
        }
    })
}

//get传参方式的ajax
function fun2(){
    $.ajax({
    url:"/indexApi2",
    type:"get",
    data:{
        Api2:'这句就是get传递参数-ajax' //这是ajax给后端的传参
        },
    success:function (res) {
    //json格式在前端是object类型
        console.log(res)
        console.log(typeof(res)) //在console打印数据类型
        $("#test3").text(JSON.stringify(res)) //object转字符串
        $("#test4").text(res.data)
        }
    })
}

//post无参方式的ajax 注意csrf
function fun3(){
    $.ajax({
    url:"/indexApi3",  //注意如果后端api的路由带/结尾,那这里post时api最后也要带/,否则500Internal Server Error
    type:"post",
    success:function (res) {
    //json格式在前端是object类型
        console.log(res)
        console.log(typeof(res)) //在console打印数据类型
        $("#test5").text(JSON.stringify(res)) //object转字符串
        $("#test6").text(res.data)
        }
    })
}

//post带参方式的ajax 注意csrf
function fun4(){
    $.ajax({
    url:"/indexApi4",  //注意如果后端api的路由带/结尾,那这里post时api最后也要带/,否则500Internal Server Error
    type:"post",
    data:{
        Api4:'这句就是post传递参数-ajax' //这是ajax给后端的传参
        },
    success:function (res) {
    //json格式在前端是object类型
        console.log(res)
        console.log(typeof(res)) //在console打印数据类型
        $("#test7").text(JSON.stringify(res)) //object转字符串
        $("#test8").text(res.data)
        }
    })
}

//提交表单
function submit1() {
    var name=$("#name").val()
    var age=$("#age").val()

    $.ajax({
        url:"/indexApi5",  //注意如果后端api的路由带/结尾,那这里post时api最后也要带/,否则500Internal Server Error
        type:"post",
        data:{
            name:name,  //这是ajax给后端表单提交的参数
            age:age
            },
        success:function (res) {
        //json格式在前端是object类型
            alert(res.msg)
            $("#test9").text(res.data)
            }
    })
}

//json格式提交表单
function submit2() {
    var id=$("#id").val();
    var sex=$("#sex").val();
    var data={
            id:id,  //这是ajax给后端表单提交的参数
            sex:sex
            }

    $.ajax({
        url:"/indexApi6",  //注意如果后端api的路由带/结尾,那这里post时api最后也要带/,否则500Internal Server Error
        type:"post",
        header:{
        "Content-Type": "application/json;charset=UTF-8"
            },
        data:JSON.stringify(data),
        success:function (res) {
        //json格式在前端是object类型
            alert(res.msg)
            $("#test10").text(res.data)
            }
    })
}

</script>

</html>

2.1.2前端部署

路由

path('index/',views.index), #   使用 django本身作为静态网页服务器 ,来部署前端页面,为了方便,这里使用同一个django,所以不包含跨域配置

视图

def index(request):
	return render(request,'test.html')

你也可以尝试用with open 打开test.html文件,将其内容给return Httpresoponse() 来模拟前端,frontend相当于render里的templates文件夹,记得render写法要配置模板位置哦
def index(request):
with open(‘frontend/test.html’,‘rb’) as f:
html = f.read()
return HttpResponse(html)

2.2#后端接口

2.2.1路由

path('indexApi/',views.indexApi),
path('indexApi2',views.indexApi2),
path('indexApi3',views.indexApi3),
path('indexApi4',views.indexApi4),
path('indexApi5',views.indexApi5),
path('indexApi6',views.indexApi6),

2.2.2视图

#无参数的get的 api(表单提交)
def indexApi(request):
    return JsonResponse({'code':200,'msg':'这是后端jsonresponse','data':'ajax-get不传参'})

#带参数的get的 api(表单提交),参数会 ?拼接ajax参数
def indexApi2(request):
    print(request.GET)
    param=request.GET
    print(param.get('Api2'))
    return JsonResponse({'code':200,'msg':'这是后端jsonresponse','data':'ajax-get传参,参数是:{0}'.format(param.get('Api2'))})



#无参数的post的 api
@csrf_exempt  #防止csrf
def indexApi3(request):
    return JsonResponse({'code':200,'msg':'这是后端jsonresponse','data':'ajax-post不传参'})

#有参数的post的 api
@csrf_exempt  #防止csrf
def indexApi4(request):
    param1=request.body
    print(param1)
    param2=request.POST
    print(param2)
    return JsonResponse({'code':200,'msg':'这是后端jsonresponse','data':'ajax-post传参,参数是:{0}'.format(param2.get('Api4'))})

#表单提交
@csrf_exempt  #防止csrf
def indexApi5(request):
    param=request.POST
    print(param)
    name=param.get('name')
    age=param.get('age')
    return JsonResponse({'code':200,'msg':'ajax post表单','data':'{}今年{}岁'.format(name,age)})

#json格式表单提交,POST无法获取
@csrf_exempt  #防止csrf
def indexApi6(request):
    # print(request.method)
    param_b=request.body
    print(param_b)
    param_dict=json.loads(param_b) #将json格式数据转换为python字典类型,即对对象进行json decode解码
    print(param_dict)
    return JsonResponse({'code':200,'msg':'ajax post json格式提交表单','data':'{}'.format(param_dict)})

3.进一步分离

真正分离的话,前后端各一个服务器

两者各自一个不同端口的django服务
前端,只部署前端部分,端口8001,ajaxurl也要带上http://后端ip+后端端口,写绝对路径不容易出错,http://不可少
后端,只部署接口部分,端口8002,配置跨域
注意跨域问题,host问题,后端设置django-cors-headers解决

使用更好的服务器
nginx部署前端项目并配置proxspass给后端
apache(+mod_wsgi)部署django后端接口
可以先单独配一个端,另一个还是django,便于测试和理解一步步来,便于理解与错误解决

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值