Ejecutar un webservice JSON con jQuery [Funciona!]

Este ejemplo asume que existe un webservice llamado wsX que retorna el siguiente string:

{ 'datos': [ {'nombre': 'Juan', 'direccion': 'Colonia 1212'}, {'nombre': 'Pedro', 'direccion': 'Mercedes 1111'} ] }


jQuery.ajax({
   type: "POST",
   url: http://X14/wsX/wsX.asmx/HelloWorld,
   data: "{}",
   contentType:"text",
   dataType:"text",
   cache: false,
   success: function(response) {
      var v = getJSON(response);
      alert("Resultado: " + v.datos[0].nombre);
   }
});
 
function getJSON(data)
{
   var s;

   s = data.substring(data.indexOf("{"));
   s = s.substring(0, s.lastIndexOf("}") + 1);
   return eval('(' + s + ')');
}
 

Utilizar eval para transformar texto a JSON

var data = "{ 'prueba': [ {'foo': 'The quick brown fox jumps over the lazy dog.' } ] }";


var v = eval('(' + data + ')');

alert("RESULTADO: " + v.prueba[0].foo);
 

Explicación de porqué viene una d en la respuesta JSON (otra mas)

Fuente: http://encosia.com/2009/06/29/never-worry-about-asp-net-ajaxs-d-again/

Explicación de porqué viene una d en la respuesta JSON

Fuente: http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/

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 

Cargar div mediante jQuery y ajax

jQuery.ajax({ url: a + '_' + trn + 'conSup.vm', async: false, cache: false, success: function(){

 

Importante!! Poner cache: false, sino sólo se ejecuta la 1ra vez.

 

 

Agregar evento change a option select html con jquery

Si se accede por el nombre de los elementos (ej sel1 y boton1)

$('[name=sel1]').change(function()
     {
   $('[name=boton1]').show();
     });

Si se accede por el id:

$('#sel1').change(function() 
     {
   $('#boton1').show();
     });

Abrir un archivo con el encoding correcto en C#

        public static Encoding GetFileEncoding(string srcFile)
        {
            // *** Por defecto usar Ansi CodePage
            Encoding enc = Encoding.Default;

            byte[] buffer = new byte[5];
            FileStream file = new FileStream(srcFile, FileMode.Open);
            file.Read(buffer, 0, 5);
            file.Close();

            if (buffer[0] == 0xef && buffer[1] == 0xbb && buffer[2] == 0xbf)
                enc = Encoding.UTF8;
            else if (buffer[0] == 0xfe && buffer[1] == 0xff)
                enc = Encoding.Unicode;
            else if (buffer[0] == 0 && buffer[1] == 0 && buffer[2] == 0xfe && buffer[3] == 0xff)
                enc = Encoding.UTF32;
            else if (buffer[0] == 0x2b && buffer[1] == 0x2f && buffer[2] == 0x76)
                enc = Encoding.UTF7;

            return enc;
        }

        public static StreamReader OpenStreamReaderWithEncoding(string srcFile)
        {
            Encoding enc = GetFileEncoding(srcFile);
            return new System.IO.StreamReader(srcFile, enc);
        }


Fuente: http://www.west-wind.com/Weblog/posts/197245.aspx

Acceder a blogger mediante Google API

Descargar Google Data API Setup(1.4.0.2).msi 

Código de ejemplo, agrega un post asignándole dos etiquetas:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Google.GData.Client;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] labels = {"label1", "label2"};        //labels que le quiero poner al post

            AddPost("titulo1", "body html", labels);     //titulo, cuerpo html y array de labels
        }

        public static bool AddPost(string title, string bodyHTML, string[] labels)
        {
            Service service = new Service("blogger", "");
            service.Credentials = new GDataCredentials("", "");
            AtomEntry newPost = new AtomEntry();
            newPost.Title.Text = title;
            newPost.Content = new AtomContent();
            newPost.Content.Content = bodyHTML;
            newPost.Content.Type = "html";
            foreach (string label in labels)
            {
                AtomCategory cat = new AtomCategory();
                cat.Scheme = new Uri("http://www.blogger.com/atom/ns#");
                cat.Term = label;
                newPost.Categories.Add(cat);
            }
            AtomEntry response = null;
            try
            {
                response = service.Insert(new Uri("http://expressraider.blogspot.com/feeds/posts/default"), newPost);
            }
            catch (GDataRequestException exception)
            {
                if (exception.ResponseString == "Blog has exceeded rate limit or otherwise requires word verification for new posts")
                {
                    return false;
                }
                else
                {
                    throw exception;
                }
            }
            if (response == null)
            {
                throw new Exception("Error inesperado");
            }
            return true;
        }

    }
}

Como evitar el doble enter en TinyMCE

Por defecto, cuando se presiona enter en un textarea configurada para utilizar el editor TinyMCE, se produce un doble salto de línea.

Para evitar esto, agregar en la configuración lo siguiente:

force_br_newlines : "true"

Ejemplo completo:

<script type="text/javascript">
tinyMCE.init({
mode : "textareas",
theme : "advanced",
theme_advanced_toolbar_location : "top",
theme_advanced_toolbar_align : "left",
force_br_newlines : "true"
});
</script>


Obtener las coordenadas de un elemento html

// ===================================================================
// Author: Matt Kruse <matt@mattkruse.com>
// WWW: http://www.mattkruse.com/
//
// NOTICE: You may use this code for any purpose, commercial or
// private, without any further permission from the author. You may
// remove this notice from your final code if you wish, however it is
// appreciated by the author if at least my web site address is kept.
//
// You may *NOT* re-distribute this code in any way except through its
// use. That means, you can include it in your product, or your web
// site, or any other form where the code is actually being used. You
// may not put the plain javascript up on your site for download or
// include it in your javascript libraries for download. 
// If you wish to share this code with others, please just point them
// to the URL instead.
// Please DO NOT link directly to my .js files from your site. Copy
// the files to your server and use them there. Thank you.
// ===================================================================

/* 
AnchorPosition.js
Author: Matt Kruse
Last modified: 10/11/02

DESCRIPTION: These functions find the position of an <A> tag in a document,
so other elements can be positioned relative to it.

COMPATABILITY: Netscape 4.x,6.x,Mozilla, IE 5.x,6.x on Windows. Some small
positioning errors - usually with Window positioning - occur on the 
Macintosh platform.

FUNCTIONS:
getAnchorPosition(anchorname)
  Returns an Object() having .x and .y properties of the pixel coordinates
  of the upper-left corner of the anchor. Position is relative to the PAGE.

getAnchorWindowPosition(anchorname)
  Returns an Object() having .x and .y properties of the pixel coordinates
  of the upper-left corner of the anchor, relative to the WHOLE SCREEN.

NOTES:

1) For popping up separate browser windows, use getAnchorWindowPosition. 
   Otherwise, use getAnchorPosition

2) Your anchor tag MUST contain both NAME and ID attributes which are the 
   same. For example:
   <A NAME="test" ID="test"> </A>

3) There must be at least a space between <A> </A> for IE5.5 to see the 
   anchor tag correctly. Do not do <A></A> with no space.
*/ 

// getAnchorPosition(anchorname)
//   This function returns an object having .x and .y properties which are the coordinates
//   of the named anchor, relative to the page.
function getAnchorPosition(anchorname) {
 // This function will return an Object with x and y properties
 var useWindow=false;
 var coordinates=new Object();
 var x=0,y=0;
 // Browser capability sniffing
 var use_gebi=false, use_css=false, use_layers=false;
 if (document.getElementById) { use_gebi=true; }
 else if (document.all) { use_css=true; }
 else if (document.layers) { use_layers=true; }
 // Logic to find position
  if (use_gebi && document.all) {
  x=AnchorPosition_getPageOffsetLeft(document.all[anchorname]);
  y=AnchorPosition_getPageOffsetTop(document.all[anchorname]);
  }
 else if (use_gebi) {
  var o=document.getElementById(anchorname);
  x=AnchorPosition_getPageOffsetLeft(o);
  y=AnchorPosition_getPageOffsetTop(o);
  }
  else if (use_css) {
  x=AnchorPosition_getPageOffsetLeft(document.all[anchorname]);
  y=AnchorPosition_getPageOffsetTop(document.all[anchorname]);
  }
 else if (use_layers) {
  var found=0;
  for (var i=0; i<document.anchors.length; i++) {
   if (document.anchors[i].name==anchorname) { found=1; break; }
   }
  if (found==0) {
   coordinates.x=0; coordinates.y=0; return coordinates;
   }
  x=document.anchors[i].x;
  y=document.anchors[i].y;
  }
 else {
  coordinates.x=0; coordinates.y=0; return coordinates;
  }
 coordinates.x=x;
 coordinates.y=y;
 return coordinates;
 }

// getAnchorWindowPosition(anchorname)
//   This function returns an object having .x and .y properties which are the coordinates
//   of the named anchor, relative to the window
function getAnchorWindowPosition(anchorname) {
 var coordinates=getAnchorPosition(anchorname);
 var x=0;
 var y=0;
 if (document.getElementById) {
  if (isNaN(window.screenX)) {
   x=coordinates.x-document.body.scrollLeft+window.screenLeft;
   y=coordinates.y-document.body.scrollTop+window.screenTop;
   }
  else {
   x=coordinates.x+window.screenX+(window.outerWidth-window.innerWidth)-window.pageXOffset;
   y=coordinates.y+window.screenY+(window.outerHeight-24-window.innerHeight)-window.pageYOffset;
   }
  }
 else if (document.all) {
  x=coordinates.x-document.body.scrollLeft+window.screenLeft;
  y=coordinates.y-document.body.scrollTop+window.screenTop;
  }
 else if (document.layers) {
  x=coordinates.x+window.screenX+(window.outerWidth-window.innerWidth)-window.pageXOffset;
  y=coordinates.y+window.screenY+(window.outerHeight-24-window.innerHeight)-window.pageYOffset;
  }
 coordinates.x=x;
 coordinates.y=y;
 return coordinates;
 }

// Functions for IE to get position of an object
function AnchorPosition_getPageOffsetLeft (el) {
 var ol=el.offsetLeft;
 while ((el=el.offsetParent) != null) { ol += el.offsetLeft; }
 return ol;
 }
function AnchorPosition_getWindowOffsetLeft (el) {
 return AnchorPosition_getPageOffsetLeft(el)-document.body.scrollLeft;
 } 
function AnchorPosition_getPageOffsetTop (el) {
 var ot=el.offsetTop;
 while((el=el.offsetParent) != null) { ot += el.offsetTop; }
 return ot;
 }
function AnchorPosition_getWindowOffsetTop (el) {
 return AnchorPosition_getPageOffsetTop(el)-document.body.scrollTop;
 }

Fuente: http://blog.crowe.co.nz/attachments/AnchorPosition.js