zoukankan      html  css  js  c++  java
  • django支持ajax的post方法

    要在django框架下使用ajax的post方法,首先要在setting.py中做如下设置:

    打开MIDDLEWARE_CLASSES 中的'django.middleware.csrf.CsrfViewMiddleware',

    MIDDLEWARE_CLASSES = (
        'django.middleware.common.CommonMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
    )

    然后在要使用ajax的模版中做配置:

    引入如下js(必须在引入jquery的js文件之后引入):

                    $('html').ajaxSend(function(event, xhr, settings) {
                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;
                }
                if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
                    // Only send the token to relative URLs i.e. locally.
                    xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
                }
            });

    然后就可以使用了·······

  • 相关阅读:
    Docker
    Docker
    Docker
    Docker
    Docker
    Docker
    pandas——向已经存在的excel数据写入data
    python——利用UI选择路径
    python——装饰器的使用
    python——生成器(协程)gevent多任务
  • 原文地址:https://www.cnblogs.com/qingxuan/p/2974968.html
Copyright © 2011-2022 走看看