Home Anotações sobre Ajax
Post
Cancelar

Anotações sobre Ajax

Instalar servidor Wamp para testes com AJAX Asynchronous Javascript And Xml Uma metodologia de programação que possibilita a comunicação assíncrona entre front-end e back-end de aplicações Web. Obter informação do servidor sem precisar recarregar a página toda.

Objeto AJAX

XMLHttpRequest

  • Objeto que disponibiliza o acesso assíncrono
    • ActiveXObject(‘Microsoft.XMLHTTP’)
  • Mesmo objeto em navegadores antigos / MS
    • Métodos
  • open: configura a transação
  • send: dispara a transação/inicia execução

Estados do processo

1
2
3
4
5
6
7
*  Propriedades * onreadystatechange //método
*  Função de tratamento de retorno * readyState
*  0 (unsent): objeto criado mas não configurado
*  1 (opened): objeto configurado mas não enviado
*  2 (headers_received): objeto enviado/aguardando resposta
*  3 (loading): retorno sendo recebido
*  4 (done): transação concluída

Estados da resposta

1
2
3
4
5
6
7
*  Propriedades * status
*  200 (ok): sucesso
*  400 (bad request): requisição inválida
*  401 (unauthorized): falta de autorização
*  403 (forbidden): acesso proibido
*  408 (request timeout): tempo hábil esgotado
*  Basicamente o sucesso é: * readyState = 4 * status = 200

Acessando o conteúdo

1
2
*  responseText * Acessa o conteúdo em formato texto
*  responseXML * Acessa o conteúdo em formato XML

Exemplos

Texto

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<!DOCTYPE html>
<html lang="pt-br">
    <head>
        <meta charset="utf-8">
        <title>AJAX (Conteúdo texto)</title>
        <script>
            /*
             * AJAX só funciona com um servidor web.
             * Não funciona pelo protocolo file://
             * Funciona apenas pelos protocolos http://, https://
             */
            var req;
            function ajaxStart()
            {
                var imagem = document.getElementById("imagemStatus");
                imagem.src = "imageLoading.gif";
                
                var url = "conteudoTexto.txt";
                
                if(window.XMLHttpRequest)
                {
                    req = new XMLHttpRequest();
                    req.onreadystatechange = ajaxProcessarRecebimento;
                    req.open("GET", url);
                    req.send(null);
                }
                else if(window.ActiveXObject)
                {
                    req = new ActiveXObject("Microsoft.XMLHTTP");
                    req.onreadystatechange = ajaxProcessarRecebimento;
                    req.open("GET", url);
                    req.send();
                }
            }
            
            function ajaxProcessarRecebimento()
            {
                if(req.readyState == 4)
                {
                    if(req.status == 200)
                    {
                        var imagem = document.getElementById("imagemStatus");
                        imagem.src = "imageEmpty.gif";
                        
                        document.getElementById("meuDiv").innerHTML = req.responseText;
                    }
                    else
                    {
                        alert(req.status + ": Possível erro.");
                    }
                }
            }
        </script>
    </head>
    <body>
        <h1>Exemplo de captura de texto via AJAX</h1>
        <input type="button" onClick="ajaxStart();" value="Obter informação de texto via AJAX">
        <br><br>
        <div id="meuDiv"></div>
        <br><br>
        <img src="imageEmpty.gif" id="imagemStatus">
    </body>
</html>

XML

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
<!DOCTYPE html>
<html lang="pt-br">
    <head>
        <meta charset="utf-8">
        <title>AJAX (Conteúdo XML)</title>
        <script>
            
            /*
             * AJAX só funciona com um servidor web.
             * Não funciona pelo protocolo file://
             * Funciona apenas pelos protocolos http://, https://
             */
            
            var req;
            
            function ajaxStart()
            {
                var imagem = document.getElementById("imagemStatus");
                imagem.src = "imageLoading.gif";
                
                var url = "conteudoXml.xml";
                
                if(window.XMLHttpRequest)
                {
                    req = new XMLHttpRequest();
                    req.onreadystatechange = ajaxProcessarRecebimento;
                    req.open("GET", url);
                    req.send(null);
                }
                else if(window.ActiveXObject)
                {
                    req = new ActiveXObject("Microsoft.XMLHTTP");
                    req.onreadystatechange = ajaxProcessarRecebimento;
                    req.open("GET", url);
                    req.send();
                }
            }
            
            function ajaxProcessarRecebimento()
            {
                if(req.readyState == 4)
                {
                    if(req.status == 200)
                    {
                        var imagem = document.getElementById("imagemStatus");
                        imagem.src = "imageEmpty.gif";
                        
                        var buffer = "";
                        buffer += "<table>";
                        buffer += "  <tr>";
                        buffer += "    <th>Curso</th>";
                        buffer += "    <th>Código</th>";
                        buffer += "    <th>Instrutor</th>";
                        buffer += "    <th>Tipo</th>";
                        buffer += "  </tr>";
                        
                        var xmlDoc = req.responseXML;
                        
                        var eSoftblue = xmlDoc.getElementsByTagName("SOFTBLUE")[0];
                        var eCourses = eSoftblue.getElementsByTagName("COURSE");
                        
                        for(var i=0; i<eCourses.length; i++)
                        {
                            buffer += "<tr>";
                            
                            buffer += "<td>" + eCourses[i]
                                               .getElementsByTagName("TITLE")[0]
                                               .firstChild
                                               .nodeValue + "</td>";
                                               
                            buffer += "<td>" + eCourses[i]
                                               .getElementsByTagName("TITLE")[0]
                                               .getAttribute("id") + "</td>";
                                               
                            buffer += "<td>" + eCourses[i]
                                               .getElementsByTagName("INSTRUCTOR")[0]
                                               .firstChild
                                               .nodeValue + "</td>";
                            
                            buffer += "<td>" + eCourses[i]
                                               .getElementsByTagName("TYPE")[0]
                                               .firstChild
                                               .nodeValue + "</td>";

                            buffer += "</tr>";
                        }
 
                        buffer += "</table>";

                        document.getElementById("meuDiv").innerHTML = buffer;
                    }
                    else
                    {
                        alert(req.status + ": Possível erro.");
                    }
                }
            }
        </script>
    </head>
    <body>
        <h1>Exemplo de captura de XML via AJAX</h1>
        
        <input type="button" onClick="ajaxStart();" value="Obter informação de XML via AJAX">
        <br><br>
        
        <div id="meuDiv"></div>
        <br><br>
        
        <img src="imageEmpty.gif" id="imagemStatus">
    </body>
</html>
Esta postagem está licenciada sob CC BY 4.0 pelo autor.