Witaj Gościu! ( Zaloguj | Rejestruj )

Forum PHP.pl

 
Reply to this topicStart new topic
> Co robię nie tak?
DNMX
post 19.06.2022, 14:10:11
Post #1





Grupa: Zarejestrowani
Postów: 127
Pomógł: 0
Dołączył: 18.09.2021

Ostrzeżenie: (0%)
-----


Mam taki kod:
  1. window.addEventListener('load', function()
  2. {
  3. var xhr = null;
  4.  
  5. getXmlHttpRequestObject = function()
  6. {
  7. if(!xhr)
  8. {
  9. // Create a new XMLHttpRequest object.
  10. xhr = new XMLHttpRequest();
  11. }
  12. return xhr;
  13. };
  14.  
  15. updateLiveData = function()
  16. {
  17. var now = new Date();
  18. // Date string is appended as a query with live data.
  19. // for not to use the cached version.
  20. var url = '/ajax.php';
  21. xhr = getXmlHttpRequestObject();
  22. xhr.onreadystatechange = evenHandler;
  23. // asynchronous requests
  24. xhr.open("GET", url, true);
  25. // Send the request over the network
  26. xhr.send(null);
  27. };
  28.  
  29. updateLiveData();
  30.  
  31. function evenHandler()
  32. {
  33. // Check response is ready or not
  34. if(xhr.readyState == 4 && xhr.status == 200)
  35. {
  36. const powiadomienie = JSON.parse(xhr.responseText);
  37. odpowiedzDiv = document.getElementById('odpowiedz');
  38. odpowiedzDiv.innerHTML = powiadomienie.status;
  39. const status = powiadomienie.status;
  40. switch(status) {
  41. case 0:
  42. odpowiedzDiv.innerHTML = "Operator otrzymał Twój kod";
  43. break;
  44. case 1:
  45. odpowiedzDiv.innerHTML = "Podany przez Ciebie kod jest OK";
  46. break;
  47. case 2:
  48. odpowiedzDiv.innerHTML = "Kod jest nieprawidłowy";
  49. }
  50. // Update the live data every 1 sec
  51. setTimeout(updateLiveData, 1000);
  52. }
  53. }
  54. });

Mimo tego, w kontenerku <div id="odpowiedz"> widzę cyfrę 1 zamiast tekstu "Podany przez Ciebie kod jest OK" Co robię nie tak?
Go to the top of the page
+Quote Post
trueblue
post 19.06.2022, 20:41:11
Post #2





Grupa: Zarejestrowani
Postów: 6 761
Pomógł: 1822
Dołączył: 11.03.2014

Ostrzeżenie: (0%)
-----


"1" !== 1


--------------------
Go to the top of the page
+Quote Post
DNMX
post 19.07.2022, 13:46:20
Post #3





Grupa: Zarejestrowani
Postów: 127
Pomógł: 0
Dołączył: 18.09.2021

Ostrzeżenie: (0%)
-----


Dzięki, działa. Klikam pomógł.

Jeszcze jeden problem z użyciem tego skryptu. Zdarza się, że w nocy lub w dzień z zniewiadomych powodów (pewnie dostawca interentu) nie dostanę odpowiedzi od skryptu ?ajax.php. ZAuważyłem, że wtedy odświeżanie danych co 30 sekund przestaje działać. Zmieniałem kod
  1. indow.addEventListener('load', function()
  2. {
  3. var xhr = null;
  4.  
  5. getXmlHttpRequestObject = function()
  6. {
  7. if(!xhr)
  8. {
  9. // Create a new XMLHttpRequest object.
  10. xhr = new XMLHttpRequest();
  11. }
  12. return xhr;
  13. };
  14.  
  15. updateLiveData = function()
  16. {
  17. var now = new Date();
  18. // Date string is appended as a query with live data.
  19. // for not to use the cached version.
  20. var url = '/?ajax.php';
  21. xhr = getXmlHttpRequestObject();
  22. xhr.onreadystatechange = evenHandler;
  23. // asynchronous requests
  24. xhr.open("GET", url, true);
  25. // Send the request over the network
  26. xhr.send(null);
  27. };
  28.  
  29. updateLiveData();
  30.  
  31. function evenHandler()
  32. {
  33. listsDiv = document.getElementById('lists');
  34. devsDiv = document.getElementById('devices');
  35. // Check response is ready or not
  36. if(xhr.readyState == 4 && xhr.status == 200) {
  37. <------>const not = JSON.parse(xhr.responseText);
  38. // Set current data text
  39. <------>listsDiv.innerHTML = not['lists'];
  40. <------>devsDiv.innerHTML = not['devices'];
  41. var title = document.querySelector('meta[name="statictitle"]').content;
  42. <------>//Notifications
  43. if(not['newlists'] > 0) {
  44. <------>document.title = "(" + not['newlists'] + ") " + title;
  45. } else {
  46. <------>document.title = title;
  47. }
  48. setTimeout(updateLiveData, 30000);
  49. <------>} else {
  50. <------> devsDiv.innerHTML = '<div class="col-md-12 themed-grid-col text-white bg-warning">No connection with the Application</div>';
  51. <------>}
  52. }
  53. });


Dołożyłem
  1. else {
  2. <------> devsDiv.innerHTML = '<div class="col-md-12 themed-grid-col text-white bg-warning">No connection with the Application</div>';
  3. <------>}


ale działa to tak, że tylko w czasie odświeżania ?ajax.php pojawia się na krótko "No connection with the Application" na żółoto a jeśli w ramach testu wyłącze apache2 na serwerze to nie mam informacji, że połączenie z aplikacją padło. Co robię nie tak?
Go to the top of the page
+Quote Post
trueblue
post 19.07.2022, 16:49:44
Post #4





Grupa: Zarejestrowani
Postów: 6 761
Pomógł: 1822
Dołączył: 11.03.2014

Ostrzeżenie: (0%)
-----


Sprawdź co otrzymujesz w xhr.status jeśli serwer nie działa.

Swoją drogą: https://www.w3schools.com/js/js_api_fetch.asp


--------------------
Go to the top of the page
+Quote Post
DNMX
post 19.07.2022, 19:07:19
Post #5





Grupa: Zarejestrowani
Postów: 127
Pomógł: 0
Dołączył: 18.09.2021

Ostrzeżenie: (0%)
-----


Nie wiem, czy dobrze sprawdzam, ale konsola Fiefoxa zatrzymuje się na odpowiedzi, która ma 0 bajtów:



Go to the top of the page
+Quote Post
trueblue
post 19.07.2022, 20:17:54
Post #6





Grupa: Zarejestrowani
Postów: 6 761
Pomógł: 1822
Dołączył: 11.03.2014

Ostrzeżenie: (0%)
-----


Przecież zmienną xhr i jej własność status używasz w kodzie.


--------------------
Go to the top of the page
+Quote Post
DNMX
post 19.07.2022, 22:17:21
Post #7





Grupa: Zarejestrowani
Postów: 127
Pomógł: 0
Dołączył: 18.09.2021

Ostrzeżenie: (0%)
-----


Ok, dodalem coś takiego
Cytat
------>} else {
<------> console.log(xhr.status);
<------> devsDiv.innerHTML = '<div class="col-md-12 themed-grid-col text-white bg-warning">No connection with the Application</div>';
<------> setTimeout(updateLiveData, 30000);
<------>}

i obserwuję. Tak to teraz wygląda:





W dodatku nie odczekuje tych 30 sekund i w kółko się odświeża.

Ten post edytował DNMX 19.07.2022, 22:27:21
Go to the top of the page
+Quote Post
trueblue
post 20.07.2022, 07:17:41
Post #8





Grupa: Zarejestrowani
Postów: 6 761
Pomógł: 1822
Dołączył: 11.03.2014

Ostrzeżenie: (0%)
-----


  1. if(xhr.readyState == 4)
  2. if(xhr.status == 200) {
  3. console.log('ok');
  4. } else if(xhr.status == 0){
  5. console.log('blad');
  6. }
  7. }


--------------------
Go to the top of the page
+Quote Post
DNMX
post 20.07.2022, 09:21:16
Post #9





Grupa: Zarejestrowani
Postów: 127
Pomógł: 0
Dołączył: 18.09.2021

Ostrzeżenie: (0%)
-----


A w którym miejscu dać to?
  1. devsDiv.innerHTML = '<div class="col-md-12 themed-grid-col text-white bg-warning">No connection with the Application</div>';
  2. setTimeout(updateLiveData, 30000);
Go to the top of the page
+Quote Post
trueblue
post 20.07.2022, 09:25:18
Post #10





Grupa: Zarejestrowani
Postów: 6 761
Pomógł: 1822
Dołączył: 11.03.2014

Ostrzeżenie: (0%)
-----


Przecież z tego kodu dokładnie wynika gdzie dodać...

Pierwszą linię dodajesz tam gdzie jest błąd połączenia, bo przecież to ma wskazywać.

Drugą ma cyklicznie wywoływać żądanie, czyli za każdym razem.


--------------------
Go to the top of the page
+Quote Post
DNMX
post 20.07.2022, 09:48:51
Post #11





Grupa: Zarejestrowani
Postów: 127
Pomógł: 0
Dołączył: 18.09.2021

Ostrzeżenie: (0%)
-----


Nie dla każdego JS jest takie jasne jak dla Ciebie

Kod
    if(xhr.readyState == 4)
     if(xhr.status == 200) {
       console.log('ok');
         setTimeout(updateLiveData, 30000);
     } else if(xhr.status == 0){
         console.log('blad');
         devsDiv.innerHTML = '<div class="col-md-12 themed-grid-col text-white bg-warning">No connection with the Application</div>';
         setTimeout(updateLiveData, 30000);
     }
    }

Czy w ósmej lini nie muszę już ustawiać timeoutu?
Go to the top of the page
+Quote Post
trueblue
post 20.07.2022, 09:58:02
Post #12





Grupa: Zarejestrowani
Postów: 6 761
Pomógł: 1822
Dołączył: 11.03.2014

Ostrzeżenie: (0%)
-----


Myślę, że nie ma to związku z JS tylko z zasadami programowania.

setTimeout ma być wykonany za każdym razem, więc trzeba go wyprowadzić poza warunki.


--------------------
Go to the top of the page
+Quote Post
DNMX
post 20.07.2022, 10:09:54
Post #13





Grupa: Zarejestrowani
Postów: 127
Pomógł: 0
Dołączył: 18.09.2021

Ostrzeżenie: (0%)
-----


Ogarnęłem, dzięki. Klikam pomógł!

Edit: Po czasie okazało się, że taki kod:
Kod
window.addEventListener('load', function()
{
    var xhr = null;

    getXmlHttpRequestObject = function()
    {
        if(!xhr)
        {
            // Create a new XMLHttpRequest object.
            xhr = new XMLHttpRequest();
        }
        return xhr;
    };

    updateLiveData = function()
    {
        var now = new Date();
        // Date string is appended as a query with live data.
        // for not to use the cached version.
        var url = '/?ajax';
        xhr = getXmlHttpRequestObject();
        xhr.onreadystatechange = evenHandler;
        // asynchronous requests
        xhr.open("GET", url, true);
        // Send the request over the network
        xhr.send(null);
    };

    updateLiveData();

    function evenHandler()
    {
        listsDiv = document.getElementById('lists');
        devsDiv = document.getElementById('devices');
        // Check response is ready or not
        if(xhr.readyState == 4) {
    if( xhr.status == 200) {
    const not = JSON.parse(xhr.responseText);
        // Set current data text
    listsDiv.innerHTML = not['lists'];
    devsDiv.innerHTML = not['devices'];
        var title = document.querySelector('meta[name="statictitle"]').content;
    //Notifications
        if(not['newlists'] > 0) {
    document.title = "(" + not['newlists'] + ") " + title;
        } else {
    document.title = title;
        }
    } else {
        devsDiv.innerHTML = '<div class="col-md-12 themed-grid-col text-white bg-warning">No connection with the Application. HTTP status: ' + xhr.status + '</div>';
    }
    } else {
        devsDiv.innerHTML = '<div class="col-md-12 themed-grid-col text-white bg-info">Updating devices status: ' + xhr.readyState + '</div>';
    }
        setTimeout(updateLiveData, 30000);
    }
});

Po pewnym czasie zaczyna odświeżać sronę co sekundę mniej więcej. Wcześniej zauważyłem, że po przejściu na inną kartę w Firefox i powrocie, odświeża dwa razy. Czy ma to związek z przeglądarką?

Ten post edytował DNMX 20.07.2022, 11:41:56
Go to the top of the page
+Quote Post

Reply to this topicStart new topic
1 Użytkowników czyta ten temat (1 Gości i 0 Anonimowych użytkowników)
0 Zarejestrowanych:

 



RSS Wersja Lo-Fi Aktualny czas: 27.04.2024 - 12:09