Django中Ajax的使用

一、前端代码

1、jquery实现

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>

<input type="button" onclick="AjaxSubmit();" value="提交">

<script src="/static/js/jquery.min.js"></script>
<script>
    function AjaxSubmit(){
        /*1、post方式发送数据*/
        $.ajax({
            url:"test_ajax/",                 // 相当于form 中的 action
            type:'POST',                  // 相当于form 中的 method
            data:{'key':'value'},         // 数据
            dataType: "json",             // 注意这个定义的是返回值的类型,不是发送数据的类型,如果返回类型不是json类型,则会进入error函数
            headers: { "X-CSRFToken": "{{ csrf_token }}" },//Django中表单提交都需要csrf验证
            success: function (arg) {     // 后端返回成功后的回调函数,data为后端传来的数据
            }
            error:function(){
            }
        });
        /*2、get方式请求数据*/
        $.ajax({
            url:"test_ajax/",                  
            type:'GET',                       
            success: function (data) {     
            }
        });
    }
</script>

</body>
</html>

 

2、js实现(比较麻烦,推荐用jquery):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript">
        function ajax1()
        {
            var request;
            if(window.XMLHttpRequest)            //首先创建XHR对象
            {
                request = new XMLHttpRequest();  //IE7+,Firefox,Chrome,Qpera,Safari
            }
            else
            {
                request =new ActiveObject("Microsoft.XMLHTTP");   //兼容IE5,IE6
            }
            //1、"GET"方法
            request.open("GET","test_ajax/",true)     //初始化一个请求
            request.send();                      //将请求发送到服务器
            //2、"POST"方法
            //request.open("POST","test_ajax/",true)
            //request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            //设置http的头信息,告诉web服务器要发送一个表单
            //request.send("name=小明&age=11"); 
            request.onreadystatechange = function()
            {
                if(request.readyState===4 && request.status===200)
                {
                    var text = request.responseText;
                    document.getElementById("div1").innerHTML= text;
                }
            }
        }

    </script>
</head>
<body>
    <input type="button" value="点一下" onclick="ajax1()">
    </br>
    <div id="div1"></div>
</body>
</html>

 

二、后端代码

1、url.py

from django.urls import path
from views import TestAjaxView

urlpatterns = [
    path('test_ajax/', TestAjaxView.as_view(), name='test_ajax'),
]

2、views.py

from django.http import HttpResponse, JsonResponse
from django.views.generic.base import View


class TestAjaxView(View):
    def get(self, request):
        return HttpResponse("helloworld!")
    def post(self, request):
        value = request.POST.get('key', '')
        # 返回json格式数据
        data = {}
        data['name'] = name
        data['age'] = age
        return JsonResponse(data)

 

三、如果使用js的方法,其中用到的几个函数解释一下

      1、open(method,url,async)函数初始化一个请求

            -mothod:发送请求方法(GET, POST)

            -url:请求地址(相对地址、绝对地址)

            -async:请求同步(false)/异步(true默认)(ajax一般使用异步请求)

         open方法中URL也可以传递参数,和其他url传递参数的使用方法一致,如果不了解可以参考这篇博客:

             Django URL传递参数的方法总结

      2、send(string)函数将请求发送到服务器

             在使用get方法时,参数都填写在url中,因此string可以不填写或null

             如果是post方法,则一定要填写参数

      3、onreadystatechange事件对服务器响应进行监听

              当request.readyState===4 && request.status===200时,说明后端数据返回正常,然后就可以通过XMLHttpRequest.responseText来获取后端传来的数据。其他获取数据的方法或属性还有:

              ·responseText:获得字符串形式的响应数据

              ·responseXML:获得XML形式的响应数据(现在比较少,一般使用JSON的格式)

              ·status和statusText:以数字和文本形式返回HTTP状态码

              ·getAllResponseHeader():获取所有的响应报头

              ·getResponseHeader(xxx):查询响应中的某个字段的值

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值