Pomoc - Szukaj - Użytkownicy - Kalendarz
Pełna wersja: [skrypt]XMLHttpRequest
Forum PHP.pl > Inne > Oceny
orson
witam ...

Po watku dostalem kilka prosb o udostepnienie tego co udalo mi sie zrobic wiec jest.

Najpierw kilka informacji:
skrypt nie nadaje sie do wiekszych zastosowan poniewaz:
trzeba dodac obsluge bledow [narazie jest generalna]
trzeba dodac cos co bedzie przechwytywac linki
rozwinac dzialanie poza divy
i wiele innych
[prosba do moderatorow: jezeli to zle forum - w sumie chce byscie ocenili jak to sie sprawuje i czy komus sie przyda - prosze przeniesc do wlasciwego]

kod:
loader.js
Kod
// Author: orson [Grzegorz Drozd]
// Test script created ONLY for www.php.pl
// You may use this script to bulid Your OWN but You must include info
// about me if you use anything from it.
// this is VERY PRE ALPHA. NO WARRANTY exclamation.gif
// ver. 0.43 [2004.02.14]
//
// to do:
//   use it :)
//   unique div name [now is 10 last chars - not good]
//   make it work not only with div [displaying etc.]

    // global flag
    var isIE = false;

    // global request and XML document
    var req;
    
    //new, lodaded document
    var loadedDoc;

    //save result [by create new div] or discard every time. bool.
    var saveResult = true;       
    
    //name of main result container
    var result = 'result';       
    
    //display "loading..." msg in the  result container questionmark.gif bool.
    //this is different than next option    
    var tempDisplayMsg = false;    
    //what to display
    var tempMsg = 'Loading ...';     

    //what to  do when document is  loading ...
    //could be with:
    // progres - show progres bar
    // screen - loading screen
    // percent - display percent
    // none - do nothing
    var loadingAction = 'progres';    

    // and id to display
    var loadingID = 'progres';    
    //display or not errors
    var showError = true;       
    //where display errors
    var showErrorIn = 'errors';


    // script begins ... do not edit it ... make Your own
    var totalBytes;
    var responseLength;
    var responsePer;
    var divId;
    var getResult = false;
    var foo = 0;
    
    function loadDoc(evt,url) {
  _hideAll();
     // W3C/IE event models to get event object
  // to do
  if (saveResult == true){
     if (document.getElementById(url.substring(parseInt(url.length)-10,parseInt(url.length))) != null){
    document.getElementById(url.substring(parseInt(url.length)-10,parseInt(url.length))).style.display = 'block';
    getResult = false;
     }else{
    getResult = true;
     }
    
  }
  // i know this is strange but if div isn't loaded yet we should be able
  // to get to load branch and this is the fastest way
  if (saveResult == false || getResult == true){
      evt = (evt) ? evt : ((window.event) ? window.event : null);
    
      if (evt) {
          //W3C/IE models to get event target reference
       try {
        _getDoc(url);
       }
       catch(e) {
        if (showError){
            var msg = (typeof e == "string") ? e : ((e.message) ? e.message : "Unknown Error");
            document.getElementById(showErrorIn).innerHTML = "Unable to get XML data:\n" + msg;
        }
        return;
       }
      }
  }
    }

    
    function _getDoc(url) {
     // branch for native XMLHttpRequest object
     divId = url.substring(parseInt(url.length)-10,parseInt(url.length));
     if (window.XMLHttpRequest) {
         req = new XMLHttpRequest();
         req.onreadystatechange = _reqStatus;
         req.open("GET", url, true);
         req.send(null);

     // branch for IE/Windows ActiveX version
     } else if (window.ActiveXObject) {
         isIE = true;
         req = new ActiveXObject("Microsoft.XMLHTTP");
         if (req) {
             req.onreadystatechange = _reqStatus;
             req.open("GET", url, true);
             req.send();
         }else{
          alert("error creating activex object");
         }
     }
    }

    // handle onreadystatechange event of req object
    function _reqStatus() {

     // only if req is valid
     if (req.readyState == 4) {
     //loaded
     if (req.status == 200) {
        
          //loaded - print
    if (saveResult == true){
        // create new div and fill it with document content
        loadedDocument = document.createElement("div");

        var divName = document.createAttribute('name');
        divName.value='resultDiv';
        loadedDocument.setAttributeNode(divName)
        loadedDocument.id = divId;
        loadedDocument.innerHTML = req.responseText;

        // ADD div to result container
        document.getElementById(result).appendChild(loadedDocument);

    }else{
        // REPLACE all in result container
        document.getElementById(result).innerHTML = req.responseText;
    }

    // if loading screen is displayed hide it to be sure or do smth else wih it.
    if (document.getElementById(loadingID) != null){
        if (document.getElementById(loadingID).style.display == "block"){
      document.getElementById(loadingID).style.display = "none";
        }
    }
     } else {
    //error
    if (showError){
        document.getElementById(showErrorIn).innerHTML = "There was a problem retrieving the XML data:\n" + req.statusText;
    }
     }
     }else {
      //still loading document
     if (tempDisplayMsg == true){
    if (req.readyState > 2) {
        document.getElementById(result).innerHTML = tempMsg;
    }
     }
  }

  // from here script don't work in ie ... i'm working on it ...
  // problem is that if doc isn't loaded ie get error on:
  // req.getResponseHeader("Content-Length") and req.responseText
  // about reposne data.
  if (!isIE && req.responseText != '') {
     //more actions or some combo questionmark.gif
     switch (loadingAction){
    case 'progres':
        totalBytes = parseInt(req.getResponseHeader("Content-Length"));
        responseLength = parseInt(req.responseText.length);
        responsePer = (100/totalBytes)*responseLength;
        document.getElementById(loadingID).style.width = Math.round(parseFloat(responsePer))+"%";
        break;
       
    case 'screen':
        document.getElementById(loadingID).style.display = "block";
        break;

    case 'percent':
        totalBytes = parseInt(req.getResponseHeader("Content-Length"));
        responseLength = parseInt(req.responseText.length);
        responsePer = Math.round((100/totalBytes)*responseLength);
        document.getElementById(loadingID).value = responsePer +" %";
        break;
     }
  }
    }
    //hide all divs with name = resultDiv
    function _hideAll(){
  var divs = document.getElementsByTagName('div');
  var i=0;

  for (i=0; i < divs.length; i++){
     if (divs.item(i).getAttribute('name') == 'resultDiv'){
    divs.item(i).style.display = 'none';
     }
  }
    }

i przykladowy plik:
  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  2. <head>
  3. <META http-equiv="Content-Type" content="text/html; charset=utf-8">
  4. body {
  5. background-color: white;
  6. font-family: verdana;
  7. font-size:12px;
  8. margin-left:15%;
  9. margin-right:15%;
  10. padding:15px
  11. }
  12. h1 {
  13. text-align:left;
  14. font-size: 130%;
  15. font-weight:bold
  16. }
  17. #loadingWindow{
  18. display: none;
  19. border: 1px solid black;
  20. background-color: red;
  21. width: 50%;
  22. height: 100px;
  23. }
  24. </style>
  25. <script type="text/javascript" src="loader.js"></script>
  26. </head>
  27. <body>
  28. <h1>XMLHttpRequest</h1>
  29. <hr>
  30. <div style="float: left; width: 150px; height: 450px; margin-right: 10px; padding: 5px; overflow: show">
  31. <b>menu</b><br />
  32. progres bar:<br />
  33. <div style="border:1px solid black; width: 100%;">
  34. <div id="progres" style="background-color: black;">&nbsp;</div>
  35. </div>
  36. <br />
  37. percent:<br />
  38. <input type="text" style="border: 1px solid black;" id="percent"><br />
  39. <br /><br /><br />
  40. links<br />
  41. <a href="#" onclick="loadDoc(event, './strony/glowna.html')">strona główna</a><br />
  42. <a href="#" onclick="loadDoc(event, './strony/about.html')">about</a><br />
  43. <a href="#" onclick="loadDoc(event, './strony/phpinfo.php')">test php</a><br />
  44. <a href="#" onclick="loadDoc(event, './jakis.xml')">brak strony [error]</a><br />
  45. </div>
  46.  
  47. <div style="border: 1px solid black; width: 460px; height: 400px; overflow:auto" id="result">
  48. <div id="loadingWindow">Loading ...</div>
  49. </div>
  50. <div style="border: 1px solid black; width: 460px; height: 40px; overflow:auto" id="errors">
  51. </div>
  52. </body>
  53. </html>

lekka edycja loader.js pozwala zobaczyc z tym plikiem rozne akcje dla ladowania dokumentu ...

pozdrawiam
Ozzy
Działa rewelacyjnie.
Wie ktoś może jak używając XMLHttpRequest można przesłać dane z formularza przy pomocy metody POST?
orson
witam ...

jest takie cos:
Kod
obj.setRequestHeader("label", "value")
... i wtedy trzeba zmienic przy send na POST i powinno dzialac ale nie testowalem tego jescze ... to jest na mojej liscie to do biggrin.gif

i jescze mala uwaga: zeby pasek postepu [albo ladowanie % albo cokolwiek innego] dzialalo dla plikow generowanych [php] to trzeba uzywac ob_start i przed wyslaniem zawartosci do przegladarki trzeba ustawic funkcja header dlugosc dokumentu ... inaczej skrypt nie wie ile bedzie danych i nie pokazuje paska postepu ...

pozdrawiam
Ozzy
Zaraz poczytam o tym setRequestHeader...
Co do header'a to się na szczęście zorientowałem, że pasuje go wysłać,
bo bez niego nie bardzo chciało działać, ale warto było się z tym pobawić smile.gif
- już widzę ten progress bar w XUL'u smile.gif

A wiesz może czemu w wizardzie (XUL) pod FF (nie wiem jak Mozillą) nie działają guziki?
(Nie ma etykiet i pojawia się błąd:
Kod
Błąd: uncaught exception: Nie udzielono uprawnieD do odczytania wBa[ciwo[ci UnnamedClass.classes

)
To jest wersja lo-fi głównej zawartości. Aby zobaczyć pełną wersję z większą zawartością, obrazkami i formatowaniem proszę kliknij tutaj.
Invision Power Board © 2001-2025 Invision Power Services, Inc.