我正在使用RoutablePageMixin通过Wagtail页面通过AJAX调用加载图像。第一次一切正常。但是,第二次单击同一图像时,AJAX调用不会调用该视图。
我尝试将click事件移到ready js函数之外,每次都创建一个新的CSRF,但没有成功。
JS:
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$('#start').click(function(evt) {
var csrftoken = Cookies.get('csrftoken');
var instance = $("#lazy").Lazy({
ajaxLoader: function(element, response) {
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
$.ajax({
url: "/ajax/",
method: "GET",
dataType: "html",
cache: false,
data: {
cosa: element.data("cosa")
},
success: function(data) {
var magnificPopup = $.magnificPopup.instance;
magnificPopup.open({
closeOnContentClick: true,
mainClass: 'mfp-img-mobile',
image: {
verticalFit: true
},
items: {
src: data
},
type: 'image'
});
response(true);
},
error: function() {
response(false);
}
});
}
});
evt.preventDefault();
});
Wahtail视图:
class HomePage(RoutablePageMixin, Page):
@route(r'^ajax/$')
def past_events(self, request):
gallery_item_id = request.GET['cosa']
image = GalleryItem.objects.filter(id=gallery_item_id).first().image
image_url = image.file.url
"""
View function for the ajax image from the gallery
"""
return HttpResponse(request.build_absolute_uri(image_url))
模板:
<div class="portfolio-hover">
<div id="start" class="action-btn">
<a id="lazy" class="" data-loader="ajaxLoader" data-cosa="{{value.id}}">
<i class="icon-basic_magnifier"></i>
</a>
</div>