Last active
December 10, 2015 21:48
-
-
Save victorvhpg/4497743 to your computer and use it in GitHub Desktop.
"Chamando WebMethod com jQuery"
simples metodo para facilitar a chamada de um webmetodo usando jQuery ajax
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
!function ($) { | |
//o metodo static webMetodo retorna um objeto jqXHR (enfim o retorno do $.ajax) | |
$.webMetodo = function (param) { | |
return $.ajax({ | |
type: "POST", | |
contentType: "application/json", | |
//aqui eh o 'payLoad' deve ser uma string no formato JSON | |
//para o servidor poder entender | |
data: JSON.stringify(param.parametros), | |
dataType: "json", | |
url: param.url + "/" + param.webMetodo, | |
//filtrar a resposta para pegar somente o objeto 'd' | |
dataFilter: function (data, type) { | |
//data eh a resposta 'pura'(string) antes do parse para objeto | |
try { | |
//pegar somente o objeto 'd' que o servidor retorna | |
//por padrao sempre o webMethod retorna um objeto JSON com | |
//uma propriedade objeto 'd' | |
//ex: { d : { dados : [1,3,4,8] } } | |
data = JSON.stringify(JSON.parse(data).d || JSON.parse(data)); | |
} catch (e) { } | |
//retorna o objeto 'd' serializado | |
return data; | |
} | |
}); | |
}; | |
} (jQuery); | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*//considerando o seguinte webmethod no arquivo "metodos.asmx" | |
[WebMethod] | |
public object Teste(int parametro1, string abc) { | |
return new { | |
dados = new String[] { "aaaa", "bbbbbb", "12312321" }, | |
mensagem = parametro1 + "-----"+ abc , | |
ok = true | |
}; | |
} | |
*/ | |
//=========================================================================== | |
//chamando o webmetodo | |
$.webMetodo({ | |
url: "metodos.asmx", | |
webMetodo: "Teste", | |
parametros: { | |
parametro1: 1, | |
abc: "teste....." | |
} | |
}).done(function (respostaJSON) { | |
console.log(respostaJSON.mensagem); | |
console.log(respostaJSON.ok); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment