Django从零开始(六)

Ajax

  Asynchronous Javascript And XML,异步 JavaScript 和 XML,是指一种创建交互式网页应用的网页开发技术。

特点:1:异步交互

   2:局部刷新

  一、Ajax局部刷新例子

    例子1:get类型

    

    点击网页的Ajax按钮,网页没有刷新,但是有新的值传递显示。通过回调函数,点击事件后指向/test_ajax页面,通过p标签显示return的值。

    html代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Ajax</title>
    <script src="/static/jquery/jquery-3.4.1.js"></script>
</head>
<body>
<h2>this is index</h2>
<button class="Ajax">Ajax</button>
<p class="content"></p>
<script>
    $(".Ajax").click(function () {
       $.ajax({
           url:"/test_ajax/  ",
           type:"get",
           {#data:"",#}
           success:function (data) {
               console.log(data);
               $(".content").html(data)
           }
       })
    })
</script>
</body>
</html>

  例子2:POST类型。

  通过ajax发送POST请求,并且获得返回值局部刷新。这个例子注意要设置csrf_token问题。

  html代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Ajax</title>
    <script src="/static/jquery/jquery-3.4.1.js"></script>
</head>
<body>
<h2>POST—Ajax</h2>
<input type="text" id="a">+<input type="text" id="b">=<input type="text" id="ret"><button class="c">计算</button>
<script>
    $(".c").click(function () {
       $.ajax({
           url:"/test_ajax/",
           type:"post",
           data:{
               "n1":$("#a").val(),
               "n2":$("#b").val(),
           },
           success:function (data) {
               console.log(data)
               $("#ret").val(data)
           }
       })
    })
</script>
</body>
</html>

views函数:

def test_ajax(request):
    n1 = int(request.POST.get('n1'))
    n2 = int(request.POST.get('n2'))
    ret = n1 + n2
    return HttpResponse(ret)

猜你喜欢

转载自www.cnblogs.com/alex2yang/p/11124410.html
今日推荐