Sítios Web II [SW2]

$('ajax')

ProfºEduardo Pezutti

http://maverick.td.utfpr.edu.br/slides/sw2 link

jQuery

AJAX

AJAX = Asynchronous JavaScript and XML

É a arte de manipular informações em uma página Web sem ter que recarregar a página!

Exemplo

jQuery e AJAX

Podemos utilizar ajax sem o jQuery, porém, já vimos que é um pouco complicado.

Com o jQuery, podemos utilizar de forma rápida o ajax: pedir conteúdo de texto, html, xml ou json de servidores remotos.

jQuery e AJAX

.load() .get() .post()
.ajax()

.load()

Escrita:
$(selector).load(URL,data,callback);


$("#div1").load("demo_test.txt");

Dentro do arquivo: demo_text.txt


<h2>jQuery and AJAX is FUN!!!</h2>
<p id="p1">This is some text in a paragraph.</p>
Exemplo

.load() Com filtro de conteúdo


$("#div1").load("demo_test.txt #p1");

Dentro do arquivo: demo_text.txt


<h2>jQuery and AJAX is FUN!!!</h2>
<p id="p1">This is some text in a paragraph.</p>
Exemplo

.load()

Parâmetro específicos para o callback

  • responseTxt - Contém o conteúdo, se a chamada tiver sucesso
  • statusTxt - Contém o estado da chamada
  • xhr - Contém o objeto XMLHttpRequest

$("button").click(function(){
  $("#div1").load("demo_test.txt",function(responseTxt,statusTxt,xhr){
    if(statusTxt=="success")
      alert("External content loaded successfully!");
    if(statusTxt=="error")
      alert("Error: "+xhr.status+": "+xhr.statusText);
  });
});
Exemplo

.get()

Escrita:
$.get(URL, dados, callback);


$("button").click(function(){
  $.get("demo_test.asp",function(data,status){
    alert("Data: " + data + "\nStatus: " + status);
  });
});
Exemplo

.post()

Escrita:
$.post(URL,callback);


$("button").click(function(){
  $.post("demo_test_post.asp",
  {
    name:"Donald Duck",
    city:"Duckburg"
  },
    function(data,status){
    alert("Data: " + data + "\nStatus: " + status);
  });
});
Exemplo

Leitor de RSS


jQuery.ajaxPrefilter(function(options) {
    if (options.crossDomain && jQuery.support.cors) {
        options.url = 'https://cors-anywhere.herokuapp.com/' + options.url;
    }
});

$.ajax({
  type: 'GET',
  url: 'https://gizmodo.uol.com.br/feed/',
  beforeSend:function(){
    // this is where we append a loading image
    $('#ajax-panel').html('<div class="loading"><img src="/img/loading.gif" alt="Carregando..." /></div>');
  },
  success:function(data){
    // successful request; do something with the data
    $('#ajax-panel').empty();
    $(data).find('item').each(function(i){
      $('#ajax-panel').append('<h4>' + $(this).find('title').text() +   '</h4><p>' + $(this).find('link').text() + '</p>');
    });
  },
  error:function(){
    // failed request; give feedback to user
    $('#ajax-panel').html('<p class="error"><strong>Oops!</strong> Aconteceu um problema, tente novmaente mais tarde.</p>');
  }
});
  
link

Site e conteúdos via ajax

link

Links

ProfºEduardo Pezutti

epsantos@utfpr.edu.br link