首页 > Web开发 > 详细

django9-ajax

时间:2019-09-29 15:27:06      阅读:69      评论:0      收藏:0      [点我收藏+]

1.ajax

  局部刷新 ,不可能每次提交请求刷新整个页面

 

2.ajax实例  

  在不刷新整个的情况下完成计算器 ,ajax的post需要添加csrftoken

  1)设置一个组件ajaxcsrf.html ,这个是通用的模板用于ajax的csrf的校验使用

{% load static %}
<script src="{% static ‘jquery.min.js‘ %}"></script>
<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;
    }

    var csrftoken = getCookie(csrftoken);


    function csrfSafeMethod(method) {
        // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    $.ajaxSetup({
        beforeSend: function (xhr, settings) {
            if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            }
        }
    });
</script>

  2)compute.html 注意的地方1.js文件放在最前面 2.jq选择id选择器不要写成name 

  选择器选中按钮--->绑定事件--->事件函数触发$.ajax

    url      #ajax的请求地址

    type     #ajax的请求类型

    data     #字典存储ajax发送到后端的数据

    sucess:function() {}   #执行成功后的操作

    error:function() {}    #执行错误后的操作

  前端的数据类型与后端数据类型不一致 ,可以通过json格式字符串的方式通信 ,转换为自己的数据类型 ,尤其是list与dict类型

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<script src="/static/js/jquery.js"></script>

<input type="text" name="num1" id="a">+
<input type="text" name="num2" id="b">=
<input type="text" name="num3" id="c">
<button id=‘b1‘>加法</button>
<br>
<input type="text">
{% include ‘ajaxcsrf.html‘ %}
<script>
    $(#b1).click(function () {
        $.ajax({
            url: /app1/compute/,
            type: post,
            data: {
                num1: $(#a).val(),
                num2: $(#b).val(),
          lst: JSON.stringify([‘game1‘,‘game2‘])                ##前端数据序列化传给后端!!!!!!!! }, success:
function (res) { console.log(res); $(#c).val(res); } }) }); </script> </body> </html>

  3)views.py和url


url(r‘compute/‘, views.compute, name=‘compute‘),

def compute(request): if request.method == ‘POST‘: a = request.POST.get(‘num1‘) b = request.POST.get(‘num2‘) c = json.loads(reqeust.POST.get(‘lst‘))            ##将前端给的json格式的str转换成py的数据类型      
     print(a,b) return HttpResponse(int(a)+int(b)) return render(request, ‘compate.html‘)

 

django9-ajax

原文:https://www.cnblogs.com/quguanwen/p/11425581.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!