A
A
Artem Gartung2020-04-19 12:47:22
JavaScript
Artem Gartung, 2020-04-19 12:47:22

How to work with ajax correctly?

Friends, there was such a problem .. Let's

start with the structure of the ajax request

$.ajax({  
        url: window.location.href,  
        cache: true,  
        success: function(html){  
            $("body").html(html);
        }  
});


The purpose of this request is to refresh the page after the modal is closed.
This approach works fine, but with a small exception:

5e9c19d7e31aa627031511.png

That is, there is a duplication of styles, and to be more precise (I will not describe HTML layout standards, I think everyone knows): the <body></body>entire structure from the container is loaded into the page body ( ) <head></head>

Question: How is it prevent? Or maybe there is some other option?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nadim Zakirov, 2020-04-19
@zkrvndm

Try one of these 2 options.
Option one:

$.ajax({  
        url: window.location.href,  
        cache: false,  
        success: function(html){
                var page = document.createElement('page'); // Создаем пустой элемент с тегом page
                page.innerHTML = html; // Записываем в него ответ сервера
                var body = page.querySelector('body').innerHTML; // Считываем с него содержимое тега body
                document.querySelector('body').innerHTML = body; // Записываем спасренный код на страницу
        }  
});

Second option:
$.ajax({  
        url: window.location.href,  
        cache: false,  
        success: function(html){
                document.write(html); // Перезаписываем текущий документ полностью
                document.close(); // Закрываем запись
        }  
});

A
Alex, 2020-04-19
@Kozack

$("body").html(html);
You need to insert not the entire response into the body, but only the contents of the tag <body>from the response

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question