Obtener datos de un web service JSON con jQuery [Funciona!]

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace Prueba1
{
    /// <summary>
    /// Descripción breve de Service1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // Para permitir que se llame a este servicio web desde un script, usando ASP.NET AJAX, quite la marca de comentario de la línea siguiente.
    [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {
        [WebMethod]
        public string HelloWorld()
        {
            return (" [{\"nombre\":\"Juan\", \"direccion\":\"Colonia 1212\"}, {\"nombre\":\"Pedro\", \"direccion\":\"Mercedes 1111\"}] ");
        }
    }
}


jQuery:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" language="javascript" src="jquery-1.3.2.min.js"></script>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Prueba personas</title>

<body>

<script type="text/javascript">

$(document).ready(function()
{

$.ajax({
 type: "POST",
 url: "http://localhost:1485/Service1.asmx/HelloWorld",
 data: "{}",
 contentType: "application/json; charset=utf-8",
 dataType: "json",
 cache: false,
 success: function(response) {
var personas = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;

for (var i = 0; i < personas.length; i++) {
alert(personas[i].nombre);
alert(personas[i].direccion);
}
 }
});


});

</script>

</body>
</html>


Fuente:
http://www.mikesdotnetting.com/Article/96/Handling-JSON-Arrays-returned-from-ASP.NET-Web-Services-with-jQuery 

No hay comentarios:

Publicar un comentario