zoukankan      html  css  js  c++  java
  • Django如何与JQuery进行数据通信?

    index.html:

    下面formaction属性表示当提交表单时,向何处发送表单数据

    <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous" async></script>
    <form action="/add/" method="get">
    	a: <input type="text" id="a" name="a" value=45> <br>
    	b: <input type="text" id="b" name="b" value=66> <br>
    	<p>result: <span id='result'></span></p>
    	<button type="button" id='sum'>提交</button>
    </form>
    

    index.js:

    使用$.get()方法进行数据通信:

    • 第一个参数指定URL,这个URL在后面的Django代码中需要对应起来。
    • 第二个参数传入参数
    • 第三个参数表示回调函数,即数据通信后需要做什么事情
    $(document).ready(function () {
        $("#sum").click(function () {
            var a = $('#a').val();
            var b = $('#b').val();
    
            $.get("/add/", {'a':a, 'b':b}, function (ret) {
                console.log(ret);
                $("#result").html(ret)
            })
        });
     });
    

    your_app/views.py:

    下面定义了两个处理函数,分别对应index.htmladd.html

    from django.shortcuts import render
    
    def index(request):
        return render(request, 'index.html')
    
    def add(request):
        c = 0
        try:
            a = request.GET['a']
            b = request.GET['b']
            c = int(a)+int(b)
        except Exception as e:
            print(str(e))
        return HttpResponse(str(c))
    

    your_app/urls.py:

    将两个URL注册到Django。

    from django.urls import path
    from . import views
    
    urlpatterns = [
        path('', views.index, name="index"),
        path('add/', views.add, name="add"),
    ]
    



    MARSGGBO原创





    2019-8-13



  • 相关阅读:
    *Convert Sorted Array to Binary Search Tree
    *Count Complete Tree Nodes
    *Binary Tree Paths
    Invert Binary Tree
    *Kth Smallest Element in a BST
    **Lowest Common Ancestor of Two Nodes in a Binary Tree
    Lowest Common Ancestor of a Binary Search Tree
    *Sum root to leaf number
    subversion javahl
    mongodb从来没有说它写成功了。
  • 原文地址:https://www.cnblogs.com/marsggbo/p/11348512.html
Copyright © 2011-2022 走看看