【发布时间】:2018-08-20 01:03:44
【问题描述】:
我正在尝试制作一些内容不断刷新的 ajax 标签。 该应用程序正在 django 1.11 上运行,因此,每个 ajax 调用都有 CSRF 脚本(如果您不熟悉,可以跳过它)
第 1 步:
通过 AJAX 调用标签内容
$('#{{ chat_friend.profile_company_user_uuid }}').click(function () {
$.ajax({
beforeSend: function (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;
}
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
},
type: "POST",
url: "/chat/view/",
data: {
id: "{{ chat_friend.profile_company_user_uuid }}", // < note use of 'this' here
access_token: $("#access_token").val()
},
success: function (data) {
$('#chat-message').html(data);
}
});
})
;
完成!
第 2 步:
按间隔调用 AJAX REFRESH
setInterval(function () {
$.ajax({
beforeSend: function (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;
}
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
},
type: "POST",
url: "/chat/refresh/",
data: {
id: "{{ opponent.profile_company_user_uuid }}", // < note use of 'this' here
access_token: $("#access_token").val()
},
success: function (data) {
$('#inner-chat').html(data);
}
});
}, 5000);
完成
但是,当我调用另一个选项卡的 AJAX 时,不会删除刷新代码,而是变为 2(或更多,取决于您切换选项卡的次数)
【问题讨论】:
标签: jquery ajax django-templates