在 Ajax 函数中将 jQuery 对象转换为 javascript

Convert jQuery object to javascript inside Ajax function

提问人:Mathieu Préaud 提问时间:11/9/2023 最后编辑:Mathieu Préaud 更新时间:11/10/2023 访问量:49

问:

我有一个用 Javascript 编写的 Ajax 函数,用于在滚动时加载帖子。网格是砌体风格(使用 Colcade JS)。

问题是我找不到将这行jQuery代码转换为Javascript的方法。我想将 Ajax 包装成一个 objet 并使用它来解析 HTML。data

const posts = $(data);

The JS:

const grid = document.querySelector(".js-grid");

    if (grid) {
        
        // Colcade JS
        var colc = new Colcade(grid, {
            columns: '.js-grid-col',
            items: '.js-grid-article'
        });
        
        // Ajax
        const current_post_type = grid.dataset.currentPostType;
        const posts_myajax = grid.dataset.postsMyajax;
        let current_page_myajax = grid.dataset.currentPageMyajax;
        const max_page_myajax = grid.dataset.maxPageMyajax;
        const ajax_url = grid.dataset.ajaxUrl;
        const current_action = grid.dataset.action;
    
        var throttleTimer;
        const throttle = (callback, time) => {
            if (throttleTimer) return;
    
            throttleTimer = true;
    
            setTimeout(() => {
                callback();
                throttleTimer = false;
            }, time);
        };
    
        const handleInfiniteScroll = () => {
            throttle(() => {
                const endOfPage = window.innerHeight + window.pageYOffset >= document.body.offsetHeight;
            
                if (endOfPage) {
                
                    const data = new FormData();
    
                    data.append( 'action', current_action );
                    data.append( 'archive_post_type', current_post_type );
                    data.append( 'query', posts_myajax );
                    data.append( 'page', current_page_myajax );
    
                    fetch(ajax_url, {
                    method: "POST",
                    body: data
                    })
                    .then((response) => response.text())
                    .then((data) => {
                        if (data) {

                            const posts = $(data);
                            colc.append(posts);

                            current_page_myajax++;
                        }
                    });
    
                }
            
                if (current_page_myajax == max_page_myajax) {
                    removeInfiniteScroll();
                }
    
            }, 1000);
        };
    
        const removeInfiniteScroll = () => {
            window.removeEventListener("scroll", handleInfiniteScroll);
        };
    
        window.addEventListener("scroll", handleInfiniteScroll);
    
    }

谢谢。

编辑

根据 @Barmar 的评论,我使用 DOMParser 来解析 HTML。项目在滚动时加载,但无法正确加载。有些项目是重复的,有些是缺失的。

const parser = new DOMParser();
const doc = parser.parseFromString(data, "text/html");
let posts = doc.querySelectorAll('.js-grid-article')

if (posts) {
    colc.append(posts);
}
JavaScript AJAX 对象

评论

0赞 Barmar 11/9/2023
您可以使用纯 JS 解析 HTML。但是,如果期望一个jQuery对象,我看不出这对您有什么帮助。DOMParserColcade.append()
0赞 Barmar 11/9/2023
@StephenP不解析 JSON,而是解析 HTML。$()
0赞 Mathieu Préaud 11/9/2023
@Barmar是的,它会解析 HTML。
0赞 Barmar 11/9/2023
我刚刚查看了 Colcade 文档。看起来你可以给 vanilla DOM 元素。因此,只需用于解析从 API 返回的 HTML。.append()DOMParser
0赞 Mathieu Préaud 11/9/2023
@Barmar直到现在我才使用过 DOMParser。在阅读您的第一条评论后,我尝试使用它,但我没有成功使其工作。你知道在这种情况下我们如何应用它吗?谢谢

答:

0赞 Barmar 11/10/2023 #1

我认为这是您的 jQuery 代码的 vanilla JS 等价物:

const parser = new DOMParser();
const posts = parser.parseFromString(data, "text/html");
colc.append(posts);

评论

0赞 Mathieu Préaud 11/10/2023
谢谢。我也尝试过这个等效项,但它在控制台中产生了一个错误。错误指向colcade js文件:此行。最后,我不知道这个问题是否仅与 Colcade 或我的代码有关。Unhandled Promise Rejection: HierarchyRequestError: The operation would yield an incorrect node treefragment.appendChild( elem );
0赞 Barmar 11/10/2023
不幸的是,Colcade 文档似乎对此没有非常详细。我不确定为什么它不喜欢这个。
0赞 Mathieu Préaud 11/10/2023
我也不确定。无论如何,非常感谢您的帮助。多亏了你,我发现:)DOMParser