您的位置:首页 > 编程语言 > Go语言

django中input type=submit 发送ajax 的post和get请求

2017-07-15 17:12 726 查看
django中input type=submit 发送ajax 的post和get请求

get请求可以直接发送

post请求会出现csrf的403错误

方法一:

input type=submit 发送post时,需要引入下面的js文件,将其放在static的js文件夹下面,

在html文件中,在jQuery插件引入之后,再引入此文件,就OK了

/**
 * Created by python on 17-7-10.
 */
$(document).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;
    }
    function sameOrigin(url) {
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            // or any other URL that isn't scheme relative or absolute i.e relative.
            !(/^(\/\/|http:|https:).*/.test(url));
    }
    function safeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});
方法二:

查看网页源代码,在form表单下面会出现一个input

<form id="post_form"  method="post" action="/center/post_site/">
<input type='hidden' name='csrfmiddlewaretoken' value='vUTGVSa2zF5ZOszbq9bV3cLqGH4bxpe8' />

在post发送参数的字典中加上一对键值:"csrfmiddlewaretoken":$('input').val(), 即获取到这个input的name和value值,传递给视图,就ok了。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: