ProfºEduardo Pezutti
http://maverick.td.utfpr.edu.br/slides/sw2 linkAJAX = Asynchronous JavaScript and XML
É a arte de manipular informações em uma página Web sem ter que recarregar a página!
ExemploPodemos 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.
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
▼
$("#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
Parâmetro específicos para o callback
$("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
Escrita:
$.get(URL, dados, callback);
$("button").click(function(){
$.get("demo_test.asp",function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
});
Exemplo
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
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
ProfºEduardo Pezutti
epsantos@utfpr.edu.br link