zoukankan      html  css  js  c++  java
  • Django——ajax简单使用

    一、简单使用总结

    1 原生js写ajax请求(写起来很复杂,而且需要考虑浏览器版本)
    2 jquery帮咱们封装好了一个方法 ajax,我们直接调用jquery的方法,就可以发送ajax的请求
    3 后期,前后端分离了,还可以继续使用jquery的ajax, axios更主流一些
    4 现在我们学的jquery的ajax方法的使用
    
    
    5 需求:通过Ajax,实现前端输入两个数字,服务器做加法,返回到前端页面
    
    6 模板
        $.ajax({
            url: '/add/',  
            method: 'post',
            data:{'a':$("#first").val() ,'b':$("#second").val() },
            success:function (data) {
                //成功触发
            },
            error:function (error) {
                //失败,触发
            }
        })
        
        
        # 默认清空下ajax会把{'a':$("#first").val() ,'b':$("#second").val() }数据转成
        # 预处理数据
        a=20&b=30,放到body体中
        # 编码默认用urlencoded

    二、详解

    index.html

    <head>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
    </head>
    
    <body>
    <input type="text" id="first">+<input type="text" id="second">=<input type="text" id="result">
    <button id="btn">点我计算结果</button>
    </body>

    views.py

    def index(request, ):
        return render(request, 'index.html')
    
    
    def add(request):
        # if request.is_ajax():
        if request.method == 'POST':
            # 取出a和b
            a = int(request.POST.get('a'))
            b = int(request.POST.get('b'))
            print(a, b)
    
            # HttpResponse返回什么,js中的data就是什么(字符串)
            return HttpResponse(a + b)

    urls.py

    from app01 import views
    urlpatterns = [
        # path('admin/', admin.site.urls),
        path('', views.index),
        path('add/', views.add),
    ]

    页面显示:

    ps: 配置中可能遇到的问题

    settings.py

    1 注释中件件中# 'django.middleware.csrf.CsrfViewMiddleware',
    2 设置SLASH=False
    3 TEMPLATES 中配置 'DIRS': [os.path.join(BASE_DIR / 'templates')]
    4 配置static路径
    STATICFILES_DIRS=[
        os.path.join(BASE_DIR,'static')
    ]
  • 相关阅读:
    C++中的动态内存管理
    Harbor镜像仓库搭建
    nexus私服搭建
    Tekton ACK安装
    容器监控实践,从入门到放弃
    Bitwarden_搭建密码服务器
    Jenkins-部署文档
    Mysql-基本的
    Zabbix添加-钉钉故障报警
    ZABBIX-4.4 yum安装
  • 原文地址:https://www.cnblogs.com/guojieying/p/13838358.html
Copyright © 2011-2022 走看看