嗨,这是一个奇怪的问题。我试图用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>
答案 0 :(得分:2)
在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