我正在编写一个聊天应用程序,如果请求的聊天id已经显示(以防止不必要的请求),我将尝试使用以下代码中止请求聊天:
htmx.logger = async function(elt, event, data) {
// cancel the request if the requested chats is already displayed.
if(event === 'htmx:beforeRequest' && data.pathInfo.requestPath.includes('display_chat')){
console.log('Logger called:', event, data);
const displayed_chat = document.getElementById('displayed-chat-info')
if(displayed_chat){
const url_params = data.pathInfo.requestPath.split('/')
const chat_id = displayed_chat.dataset.displayedChat
// if the id of the displayed chat is the same as requested chat id
// abort the request
if(chat_id === url_params[url_params.length - 1]){
data.xhr.abort()
htmx.trigger(elt, 'htmx:abort')
}
}
}
}
htmx.logger()
问题是,我已经调试了所有东西,除了htmx:abort没有中止请求之外,一切都“正常”。
我检查了htmx:abort事件是否首先被触发,它是,我还检查了获取中止事件的html元素(elt)是否与发出beforeRequest的元素相同,我不知道发生了什么,我已经检查了文档,我的代码应该可以工作,因为据说
"This event is triggered before an AJAX request is issued. If the event is cancelled, no request will occur."
请记住,htmx记录器中的“event”是一个字符串,而不是一个实际的事件,所以我不能在这里使用event.preventDefault()。