*Django中的Ajax jq的书写样式1

导入插件,导入jquery,json是添加的json文件

Ajax的get请求与post请求

urls.py

python 复制代码
path('in3/',views.in3),

views.py

python 复制代码
def in3(request):
    return render(request,'07.html')

要返回数据的path没有写,html就是下面图片中控制台的内容,记得传递参数

07.html【get请求】

html 复制代码
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="{% static 'jquery-3.6.0.min.js' %}"></script>
</head>
<body>
    用户名:<input type="text"><br>
    密码:<input type="password">
    <button>send</button>
    <script>
        $('button').click(function (){
            $.ajax({
                url:'/p2/',
                method:'get',
                data: {
                    name:$('input[type=text]').val(),
                    pwd:$('input[type=password]').val(),
                },
                // 上面的data是传入数据,下面的data是返回的数据
                success:function (data){
                    console.log(data)
                },
                error:function (xhr, status, error){
                    console.log(error)
                }
            })
        })
    </script>
</body>
</html>

07.html【post请求】

html 复制代码
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    {% csrf_token %}
    <script src="{% static 'jquery-3.6.0.min.js' %}"></script>
</head>
<body>
    用户名:<input type="text"><br>
    密码:<input type="password">
    <button>send</button>
    <script>
        function getCookie(name) {
            var cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = jQuery.trim(cookies[i]);
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) === (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
        $(function (){
            $('button').click(function (){
                $.ajax({
                    url:'/p2/',
                    method:"post",
                    data: {
                        name:$('input[type=text]').val(),
                        pwd:$('input[type=password]').val(),
                    },
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("X-CSRFToken", getCookie("csrftoken"));
                    },
                    success:function (data){
                        console.log(data)
                    }
                })
            })
        })
    </script>
</body>
</html>

post请求比get请求要多一个csrf请求头,不写报404错误

绝大多数情况使用get,传递密码这些用post,post只是相对于get安全点

edge浏览器

Google浏览器

请求头,返回数据都是一样的,有报错的话,还是使用谷歌浏览器,Edge浏览器有些报错信息写的不详细

Json文件

json文件要放在static文件下才会识别到

data.json

html 复制代码
{
  "total": 4,
  "data": [
    {
      "name": "三国演义",
      "category": "文学",
      "desc": "一个军阀混战的年代"
    },{
      "name": "三国演义2",
      "category": "文学2",
      "desc": "一个军阀混战的年代2"
    }
  ],
  "obj": {"adf": "adf"}
}

urls.py

python 复制代码
#获取json数据
path('in4/',views.in4)

#json数据
path('gjson/', views.Jsond, name='gjson'),

views.py

python 复制代码
def Jsond(request):#JsonResponse(json文件)
    with open('static/data.json', 'r') as json_file:
        data = json.load(json_file)
    response = JsonResponse(data)

    # 设置X-Content-Type-Options头部
    response['X-Content-Type-Options'] = 'nosniff'

    return response


def in4(request):
    return render(request,'08.html')

json也可以写为这样,不过要导入JsonResponse

python 复制代码
from django.http import JsonResponse

def Jsond(request):#JsonResponse(json文件)
    with open('static/data.json', 'r') as json_file:
        data = json.load(json_file)

    return JsonResponse(data)

08.html

html 复制代码
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="{% static 'jquery-3.6.0.min.js' %}"></script>
    <style>
        h3{
            color:darkorange;
        }
    </style>
</head>
<body>
    <button>click</button>
    <hr>
    <ul>
        <!-- 存放ul -->
    </ul>
<script>
    $(function (){
        $('button').click(function (){
            $.ajax({
                url:'/static/data.json',
                method:'get',
                cache: false,
                success:function (da){
                    {#console.log(da)//直接就是json格式#}
                    arr=da.data
                    str=''
                    for(var i=0;i<arr.length;i++){
                        {#网络不稳定时会报错但不影响使用#}
                        str+=`<li>
                                        <h3>书名:${arr[i].name}</h3>
                                        <h6>类别:${arr[i].name}</h6>
                                        <p>简介:${ arr[i].desc}</p>
                                    </li>`;
                    }
                    $('ul').html(str)
                },
                error:function (xhr,status,error){
                    console.log(error)
                }
            })
        })
    })
</script>
</body>
</html>

这里多了cashe,默认为true,缓存请求的数据至浏览器,以减少下次请求时间,【改变json文件后,需要改为false或关闭浏览器重新启动服务器,用以清除缓存好的数据】

点击click后

相关推荐
GoGeekBaird2 小时前
69天探索操作系统-第66天:为现代操作系统设计高级实时进程间通信机制
后端·操作系统
G皮T2 小时前
【Python Cookbook】文件与 IO(二)
python·i/o·io·文件·gzip·stringio·bytesio
还是鼠鼠2 小时前
单元测试-概述&入门
java·开发语言·后端·单元测试·log4j·maven
封奚泽优3 小时前
使用Python绘制节日祝福——以端午节和儿童节为例
人工智能·python·深度学习
干啥都是小小白3 小时前
话题通信之python实现
python·机器人·ros
仟濹3 小时前
「数据采集与网络爬虫(使用Python工具)」【数据分析全栈攻略:爬虫+处理+可视化+报告】
大数据·爬虫·python·数据挖掘·数据分析
水银嘻嘻4 小时前
03 APP 自动化-定位元素工具&元素定位
python·appium·自动化
蹦蹦跳跳真可爱5894 小时前
Python----目标检测(《用于精确目标检测和语义分割的丰富特征层次结构》和R-CNN)
人工智能·python·深度学习·神经网络·目标检测·cnn
我最厉害。,。4 小时前
接口安全&SOAP&OpenAPI&RESTful&分类特征导入&项目联动检测
后端·restful
抽风的雨6104 小时前
【python深度学习】Day 42 Grad-CAM与Hook函数
开发语言·python·深度学习