您好,这是一个奇怪的问题。我正在尝试为Django提供以下index.htm文件。当您单击按钮时,页面(而不是服务器)会进行跨域请求。如果我直接在浏览器中加载索引文件,它将起作用。但是,如果我将其与django一起使用,则会在同一浏览器(Safari)中收到“尝试加载资源时发生错误”。我正在对跨域请求使用(YQL)此方法:http://james.padolsey.com/javascript/cross-domain-requests-with-jquery/

<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src="/static/jquery-1.10.0.min.js"></script>
<script type='text/javascript' src="/static/jquery.xdomainajax.js"></script>
<script>
function myFunction()
{
    $.ajax({
        url: 'http://www.google.com',
        type: 'GET',
        success: function(res) {
        var headline = $(res.responseText).text();
            document.getElementById("demo").innerHTML=res;
        },
    beforeSend : function(xhr, settings) {
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhr.setRequestHeader("Cache-Control", "no-cache");
        if (!csrfSafeMethod(settings.type)) {
            xhr.setRequestHeader("X-CSRFToken", getCookie("csrftoken"));
        }
    }
    });
}
function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
</script>

</head>
<body>

<button onclick="myFunction()">Click me</button>

<p id="demo"></p>

</body>

</html>

最佳答案

在您的ajax函数中添加以下代码:

    beforeSend : function(xhr, settings) {
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhr.setRequestHeader("Cache-Control", "no-cache");
        if (!csrfSafeMethod(settings.type)) {
            xhr.setRequestHeader("X-CSRFToken", getCookie("csrftoken"));
        }
    },


还有脚本中的此功能:

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


:D

07-28 06:37