JQuery window.location не работает - PullRequest
0 голосов
/ 28 августа 2018

Я использую JQuery и добавляю прослушиватель событий на кнопку-флажок. Я хочу отправить другой запрос на сервер, в зависимости от того, установлен флажок или нет. когда я все утешаю, кажется, что все в порядке, но когда я добавляю window.location.assign, он не работает должным образом.

Вот мой кусок кода:

<input class="form-check-input" type="checkbox" value="" id="isPageNoSorted">

<script>
    $('#isPageNoSorted').change(function() {
        isPageNoSorted = !isPageNoSorted

        $.get('/bookShow/' + isPageNoSorted  + '/' + <%= currentPage%> ).done(function(data) {
            console.log('/bookShow/' + isPageNoSorted  + '/' + <%= currentPage%>)
            //window.location.assign('/bookShow/' + isPageNoSorted  + '/' + <%= currentPage%>)
        })
    })
</script>

код моего сервера:

router.get('/bookShow/:isPageNoSorted/:page', (req, res) => {
    var isPageNoSorted = req.params.isPageNoSorted;
    var page = req.params.page || 1;
    var perPage = 5;
    if (isPageNoSorted == "true") {
        bookModel.find({
                isDeleted: false
            }).sort('-pageCount')
            .skip((perPage * page) - perPage)
            .limit(perPage)
            .exec((err, data) => {
                if (data) {
                    if (data.length > 0) {
                        bookModel.find({
                            isDeleted: false
                        }).count().exec((err, count) => {
                            res.render(
                                'main/bookShow', {
                                    books: data,
                                    pages: Math.ceil(count / perPage),
                                    currentPage: page,
                                    isPageNoSorted: isPageNoSorted
                                }
                            );
                        })
                    } else {
                        res.send("Not enough data! Hajiiii :))")
                    }
                } else if (err) {
                    console.log(err)
                }
            })
    } else {
        bookModel.find({
                isDeleted: false
            }).sort('-createdAt')
            .skip((perPage * page) - perPage)
            .limit(perPage)
            .exec((err, data) => {
                if (data) {
                    if (data.length > 0) {
                        bookModel.find({
                            isDeleted: false
                        }).count().exec((err, count) => {
                            res.render(
                                'main/bookShow', {
                                    books: data,
                                    pages: Math.ceil(count / perPage),
                                    currentPage: page,
                                    isPageNoSorted: isPageNoSorted
                                }
                            );
                        })
                    } else {
                        res.send("Not enough data! Hajiiii :))")
                    }
                } else if (err) {
                    console.log(err)
                }
            })
    }
});

после раскомментирования window.location console.log больше ничего не регистрирует. Запрос отправляется на тот же URL, и страница просто обновляется.

ПРИМЕЧАНИЕ Я попробовал другой способ решения этой проблемы. Решение заключается в следующем:

$('#isPageNoSorted').change(function () {
            isPageNoSorted = !isPageNoSorted
            $.get('/bookShow/' + isPageNoSorted  + '/' + <%= currentPage%> ).done(function(data) {
                $('html').html(data.replace(/<html>(.*)<\/html>/, "$1"));
            })
        })

но я сталкиваюсь с новой ошибкой:

Невозможно прочитать свойство 'appendChild' с нулевым значением

Я действительно нахожусь в глуши, ожидая увидеть хорошее решение.

1 Ответ

0 голосов
/ 28 августа 2018

Синтаксис для присвоения приведен ниже:

location.assign("https://www.w3schools.com");

Вам необходимо передать полный URL-адрес. Другое дело, что вам не нужно использовать запрос $ get. Измените ваш код, как показано ниже, и он будет работать как шарм.

<input class="form-check-input" type="checkbox" value="" id="isPageNoSorted">

<script>
    $('#isPageNoSorted').change(function() {
        isPageNoSorted = !isPageNoSorted

         $.get('/bookShow/' + isPageNoSorted  + '/' + <%= currentPage%> ).done(function(data) {
        console.log(data);
        //process the data and convert to html formatand replace with old one.
    }) 
        
    })
</script>

Пожалуйста, замените http://www.example.com на ваш URL.

...