最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - refresh a same page without reloading? - Stack Overflow

programmeradmin2浏览0评论

I have already asked this question here but none of the answers were working. I have a messaging app in Django where users can send messages each other. I want to refresh the page so that the user can see new messages. But there is one problem if the user is writing a message and I try to reload the page every x-minutes the message that the user was writing will disapear. So how can I avoid this?

/*This is one of the solutions that I have tried*/
window.location.reload(true);
history.go(0);
window.location.href=window.location.href;

messages.html:

{% extends 'profile/base.html' %}
{% load tz %}
{% block title %}
Messages
{% endblock %}
{% block head %}
  <link rel="stylesheet" href=".5.2/css/bootstrap.min.css">
  <script src=".5.1/jquery.min.js"></script>
  <script src=".js/1.16.0/umd/popper.min.js"></script>
  <script src=".5.2/js/bootstrap.min.js"></script>
  <link rel="stylesheet" href=".3.7/css/bootstrap.min.css">
  <style>
          #form {
            position: fixed;
            bottom: 0;
            background-color:#f1f1f1;
          }
.container {
  border: 1px solid #dedede;
  background-color: #f1f1f1;
  border-radius: 5px;
  padding: 1px;
  margin: 1px 0;
}


.container::after {
  content: "";
  clear: both;
  display: table;
}

.darker {
  border-color: #ccc;
  background-color:#ddd;
}

.container img {
  float: left;
  max-width: 40px;
  height:40px;
  width: 100%;
  margin-right: 20px;
  border-radius: 50%;
}

.time-left {
  margin-left:61px;
  color: #999;
}

h4 {
    display:inline;
}
    </style>
{% endblock %}
{% block content %}
{% if not chat %}
    <div class="container">
         Impossible de mencer un chat avec cet utilisateur ou bien vous n'avez pas acces a ce chat.
    </div>
{% else %}
    {% if chat %}
        <div id ='bottom' class="panel">
                {% for message_item in chat.message_set.all %}
                {% url 'profile' message_item.author.pk as the_user_url%}
    {% if message_item.is_readed %}
    <div class="container">
    {% else %}
    <div class="container darker">
    {% endif %}
    <a href="{{ the_user_url }}">

  <img src="{{ message_item.author.profile.avatar.url }}" alt="Avatar" style="width:100%;">
  <h4><a href="{{ the_user_url }}">{{ message_item.author.profile.prenom|title }}</a></h4>
  <p>{{ message_item.message }}</p>
  <span class="time-left">{{ message_item.pub_date|utc }}</span>
  </a>
</div>

                {% endfor %}
                <br><br><br><br>
            </div>
        </div>
    {% endif %}

    <div class='w3-container'>
    <div id='form'>
        <form method="post" action='{% url 'messages' chat.id %}'>
            {% csrf_token %}
            {{ form.as_p }}

            <input type="submit" value='envoyez' />
            </form>
        </div>
        </div>
        <script src=".8.1.min.js"></script>
        <script>
        $('document').ready(function() {
           $('html').animate({scrollTop: document.body.scrollHeight},1);
        });
        </script>
{% endif %}
{% endblock %}

urls.py:

from django.urls import path
from . import views

urlpatterns = [
    path('dialogs/<int:chat_id>/',views.MessagesView.as_view(), name='messages'),
    ]

I have already asked this question here but none of the answers were working. I have a messaging app in Django where users can send messages each other. I want to refresh the page so that the user can see new messages. But there is one problem if the user is writing a message and I try to reload the page every x-minutes the message that the user was writing will disapear. So how can I avoid this?

/*This is one of the solutions that I have tried*/
window.location.reload(true);
history.go(0);
window.location.href=window.location.href;

messages.html:

{% extends 'profile/base.html' %}
{% load tz %}
{% block title %}
Messages
{% endblock %}
{% block head %}
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn./bootstrap/4.5.2/css/bootstrap.min.css">
  <script src="https://ajax.googleapis./ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare./ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn./bootstrap/4.5.2/js/bootstrap.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn./bootstrap/3.3.7/css/bootstrap.min.css">
  <style>
          #form {
            position: fixed;
            bottom: 0;
            background-color:#f1f1f1;
          }
.container {
  border: 1px solid #dedede;
  background-color: #f1f1f1;
  border-radius: 5px;
  padding: 1px;
  margin: 1px 0;
}


.container::after {
  content: "";
  clear: both;
  display: table;
}

.darker {
  border-color: #ccc;
  background-color:#ddd;
}

.container img {
  float: left;
  max-width: 40px;
  height:40px;
  width: 100%;
  margin-right: 20px;
  border-radius: 50%;
}

.time-left {
  margin-left:61px;
  color: #999;
}

h4 {
    display:inline;
}
    </style>
{% endblock %}
{% block content %}
{% if not chat %}
    <div class="container">
         Impossible de mencer un chat avec cet utilisateur ou bien vous n'avez pas acces a ce chat.
    </div>
{% else %}
    {% if chat %}
        <div id ='bottom' class="panel">
                {% for message_item in chat.message_set.all %}
                {% url 'profile' message_item.author.pk as the_user_url%}
    {% if message_item.is_readed %}
    <div class="container">
    {% else %}
    <div class="container darker">
    {% endif %}
    <a href="{{ the_user_url }}">

  <img src="{{ message_item.author.profile.avatar.url }}" alt="Avatar" style="width:100%;">
  <h4><a href="{{ the_user_url }}">{{ message_item.author.profile.prenom|title }}</a></h4>
  <p>{{ message_item.message }}</p>
  <span class="time-left">{{ message_item.pub_date|utc }}</span>
  </a>
</div>

                {% endfor %}
                <br><br><br><br>
            </div>
        </div>
    {% endif %}

    <div class='w3-container'>
    <div id='form'>
        <form method="post" action='{% url 'messages' chat.id %}'>
            {% csrf_token %}
            {{ form.as_p }}

            <input type="submit" value='envoyez' />
            </form>
        </div>
        </div>
        <script src="http://code.jquery./jquery-1.8.1.min.js"></script>
        <script>
        $('document').ready(function() {
           $('html').animate({scrollTop: document.body.scrollHeight},1);
        });
        </script>
{% endif %}
{% endblock %}

urls.py:

from django.urls import path
from . import views

urlpatterns = [
    path('dialogs/<int:chat_id>/',views.MessagesView.as_view(), name='messages'),
    ]
Share Improve this question edited Feb 13, 2021 at 13:19 Thierno Amadou Sow asked Feb 13, 2021 at 12:00 Thierno Amadou SowThierno Amadou Sow 2,5732 gold badges7 silver badges19 bronze badges 4
  • you can use ajax to refresh the messages, or use session to svae a messages. – Max Commented Feb 13, 2021 at 12:13
  • If you're writing a messaging system, look in to using Websockets. That way you avoid the problem of refreshing the page causing the content the user was typing to be lost, and also avoids the need for AJAX polling which will cause server performance issues. – Rory McCrossan Commented Feb 13, 2021 at 12:24
  • @ming i am new in django and web developpement and for now i just need to use ajax can anyone give me an idea how to do it in ajax or using sessions – Thierno Amadou Sow Commented Feb 13, 2021 at 12:27
  • Just search regarding ajax and JavaScript, this site does not replace relevant documentation and tutorials but it is for concise questions stackoverflow./help/how-to-ask – iklinac Commented Feb 13, 2021 at 12:56
Add a ment  | 

4 Answers 4

Reset to default 2

For a messaging app, it's better to not reload the page, instead use Ajax/fetch and just call your get-messages request, then show messages in the page, for example:

const getMessages = ()=>{
fetch("https://jsonplaceholder.typicode./ments") // use your messages request url, this is a sample
  .then((response) => response.json())
  .then((messages) => {
    let messagesHtml = "";
    for (var message of messages) {
    
      messagesHtml += `<div>${message.name}</div>`; // use your message html structure here
    }

    let messagesContainer = document.getElementById("messagesContainer");
    messagesContainer.innerHTML = messagesHtml;
  })
  .catch((err) => console.log(err));
}

  
  setInterval(getMessages, 3000);
<div id="messagesContainer"></div>

If you have to reload the page, you can check the last time that user was typing and reload the page with a delay, for example listen to keypress and set a variable that you can handle page reload with that:

reloadDelay = 0;
function setDelayForReload(){
  reloadDelay = 3000;
}

function reloadPage(){
if(reloadDelay == 0){
  window.location.reload()
}

}
setTimeout(reloadPage, 3000)
<body onkeypress="setDelayForReload()">
  <div id="messagesContainer"></div>
</body>

That would more likely be something like this:

<input type="text" value="<?php    if (isset($_POST['username'])) {        echo htmlspecialchars($_POST['username'], ENT_QUOTES);    }?>" name="username">

Make sure you escape any data before echoing it to the browser (as per the above example) – otherwise, what would happen if the user entered a " into the username box?

It is called web 2.0 and you don't need to load a page again. The most interactive pages have only 1 page and everything is then loaded in background.

You can then deliver your page as Pwa for example.

To get the contents of another page, you should use the fetch() function.

https://developer.mozilla/en-US/docs/Web/API/Fetch_API/Using_Fetch

It returns a promise. In this way you don't need to set any callback.

There could be multiple ways to achieve this

  1. save the content of the input field where the user is typing into local storage and after reloading the page repopulate that input field
  2. use Ajax to check whether more messages are created and just populate the messages without reloading anything.
  3. use services like firebase or pusher. it can be used to get Async updates when you get new messages
  4. use socket programming to get updates and only change the relevant part of dom
发布评论

评论列表(0)

  1. 暂无评论