9 HTML&JS等前端知識系列之Ajax post請求帶有token向Django請求


我們 在母板上寫入這段代碼:
    <script type="text/javascript">
        // 個人定義大函數,不是重點,可以忽略
        $(document).ready(function(){
            get_sys_load();           
            var active_node = $("#mainnav-menu a[href='{{ request.path }}']");
            active_node.parent().addClass("active-link");
            if (active_node.parent().parent().hasClass("collapse")){
                active_node.parent().parent().addClass("in");
            }

        });//end doc ready
        // 個人定義大函數,不是重點,可以忽略
        function  get_sys_load(){
            $.ajax({
                url: "{% url 'get_server_host_status' %}",
                type: "GET",
                dataType: "json",
                success: function(callback){
                    for( i in callback){
                            console.log(i,callback[i]);
                            $('#'+ i +'_display').text(callback[i]);
                            $('#'+ i +'_width').text(callback[i]);
                            $('#'+ i +'_attr').css('width',callback[i]+'%')

                    }// end for
                },// end sucess func
                error: function(callback){
                    alert(callback)
                }// end error func
            })
        }
        
        // 這個才是重點的代碼,必須寫
        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;
        }

        // 這個才是重點的代碼,必須寫
        function csrfSafeMethod(method) {
            // these HTTP methods do not require CSRF protection
            return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
        }
        
        csrftoken = getCookie('csrftoken');
        $.ajaxSetup({  //添加頭部信息,csrftoken, 把token塞入頭部
            beforeSend: function(xhr, settings) {
                if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                    xhr.setRequestHeader("X-CSRFToken", csrftoken);
                }
            }
        });
    
    </script>
    {% block  bottom-js %}
    {% endblock %}

我們在子板上調用這端js代碼,調用的前提是子板的html頁面必須嵌套了這個 csrf_token, 代碼如下

html頁面的代碼:
==================
<span>{% csrf_token %}</span>
==================



======JQuery代碼 =======

{% block  bottom-js %}
<script>

    function run_cmd(){  //由於  ajaxSetup 設置好了token,所以我們可以直接提交數據了!     
        var input_cmd = $('textarea').val();
        $.ajax({
            url:"{% url 'put_cmd' %}",
            type:'POST',
            dataType:'json',             
            data:{'host_id':$('#host_id').text(),'minion_name':$('#minion_id').text(),'cmd':input_cmd},
            success: function(callback){
                console.log(callback)
            }, // end success
            error: function (callback) {
                console.log(callback);
                $('code').append(callback)
            }
        })
    }

    function show_result(content){

    }

</script>

{% endblock %}

此時,我們在提交post請求,就能夠正常提交了,可以參考官網的信息:https://docs.djangoproject.com/en/dev/ref/csrf/#ajax。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM