miércoles, 11 de noviembre de 2009

Como llamar un servicio web en asp.net desde jquery y retornar un documento xml

En este articulo vamos a mostrar como programar un servicio web en asp.net 2.0 y retornar un documento xml. Luego de crear el servicio y retornar el documento xml vamos hacer la llamada utilizando el ajax de jquery. El código mostrado en este ejemplo es vb.net.
Este es el código del servicio web.
Agregas un servicio web a tu projecto que se llame Service.

Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Xml
Imports System.Data
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<System.Web.Script.Services.ScriptService()> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class Services
Inherits System.Web.Services.WebService

Dim xmlDoc As New XmlDocument
<Web.Services.WebMethod()> _
Public Function checkuser(Byval UserName as string, Byval Password as string) As XmlDocument
Try
xmlDoc = New XmlDocument
Dim result As String = ""
If UserName = "Pablo" and Password = "12345" then
result = "True"
else
result = "False"
end if

xmlDoc.LoadXml("<result val='" & result & "'>" & result & "</result>")
Return xmlDoc
Catch ex As Exception
xmlDoc.LoadXml("<result val='False'>False</result>")
Err.Clear()
Return xmlDoc
End Try

End Function

End Class


Código para llamar el servicio web desde jquery
function checkuser(){
var params = 'UserName=Pablo&Password=12345';
var doc;
var result = new Array();
var rtn;

$.ajax({
type: "GET",
url: "Services.asmx/CheckUserName",
data: params,
timeout: 30000,
beforeSend: function(xhr){
xhr.setRequestHeader("Content-Length", params.length);

},
dataType: "xml",
complete: function(xhr, data){

if (xhr.status == 200) {
//este if verifica si el explorador puede utilizar el XMLDOM ActiveX
if (window.ActiveXObject) {
doc = new ActiveXObject("Microsoft.XMLDOM");
doc.async = false;
doc.loadXML(xhr.responseText);

rtn = doc.text;
result = rtn.split("_")

if (result[0] == 'True') {


alert('Es buena la información');

}
else {
$('#lblmsg').html('Invalid User Name');
}

}
else {
var dat;
dat = xhr.responseText;
//si no soporta XMLDOM ActiveX utiliza un loop de jquery para localizar los valores dentro del documento xml
$(xhr.responseXML).find("result").each(function(){

rtn = $(this).attr("val");
result = rtn.split("_")
if (result[0] == 'True') {


alert('Es buena la información');

}
else {
$('#lblmsg').html('Invalid User Name');

}

});

}
}

else {

alert("Service Error!");
}

//alert(result)

}

});

}
ahora los que nos resta es llamar la función que ejecuta el servicio web

    function btnCallService_onclick() {
checkuser()
}

</script>
<input id="btnCallService" type="Button" value="Call Service" onclick="return btnCallService_onclick()" />
Espero que les sea útil.

No hay comentarios:

Publicar un comentario