Con la función json_encode podemos convertir un objecto php (array multidimensional) en objecto javascript.
/* definición de objecto php */
$arrayPhp = array(
'key0' => array(
atributo1 => valor1,
atributo2 => valor2,
atributo3 => valor3
),
'key1' => array(
atributo1 => valor1,
atributo2 => valor2,
atributo3 => valor3
)
);
/* conversión de objeto php a json */
<?php $objJson = json_encode($arrayPhp); ?>
Ahora ya tenemos un objeto json que podemos inyectar en funciones javascript e inicializar nuestros objetos javascript.
/* inicialización de objectos javascript a través del objeto json */
<div data-ng-init='inicializarAngularJs($objJson)'></div>
/* Se supone un entorno que soporta angular en el html. La función inicializarAngularJS puede inicializar objectos de clase en angular
ejemplo.
*/
$scope.inicializarAngularJS = funcion(pObj){
$scope.dat.miObjetoAngular = pObj;
}
/*
Ahora miObjetoAngular estará inicializado con el contenido de $arrayPhp y podremos accder a propiedades como: $scope.dat.miObjetoAngular.key0.atributo1 cuyo contenido será valor1
*/
¡Importante! Cuida los detalles. La función inicializarAngularJS va entre comillas simples, debido a que la conversión del objeto json usa internamente comillas dobles y podemos tener problemas. El parámetro se pasa directamente sin entrecomillar.
Nota: Si usamos caracteres que pueden generar conflictos (comillas dobles que rompan la cadena de código...) debemos "limpiar" el contenido del objJson.
Para limpiar caracteres "problemáticos de codificar" podemos usar la función de reemplazo:
$pString = str_replace("'", '', $varALimpiar);
$varALimpiar = preg_replace('/[^a-zA-Z0-9\']/', ' ',$pString);
el contenido de $varALimpiar sería eliminando las comillas simples y todos los caracteres que no fuesen letras de la a-z mayusculas o minusculas y numeros.
Saludos!
Mostrando entradas con la etiqueta javascript. Mostrar todas las entradas
Mostrando entradas con la etiqueta javascript. Mostrar todas las entradas
miércoles, 3 de agosto de 2016
jueves, 8 de octubre de 2015
Código de ejemplo para prettyPhoto
prettyPhoto Example
A gallery that does more than images
Introduction
All examples and code modified from: http://www.no-margin-for-errors.com/projects/prettyphoto-jquery-lightbox-clone/
Lightbox is a common way to easily create an image gallery. Lightbox used to use two JavaScript libraries named Prototype and Scriptaculous. These are both good. HoweverjQuery seems to be the dominant library. Lightbox has recently switched to jQuery.
Even so it doesn't have some of the capabilities to show many different kinds of content (like video or whatever). I'm showing you how to do a similar thing with prettyPhoto which is also some JavaScript built on top of the jQuery library. Once you have the jQuery library installed in your site you will have a lot of other options to add other interactivity to your site. There are literally thousands of tutorials and extensions for jQuery.
- http://docs.jquery.com/Tutorials
- http://net.tutsplus.com/articles/web-roundups/jquery-for-absolute-beginners-video-series/
- http://resources.savedelete.com/27-best-websites-for-free-jquery-tutorials.html
Here's how it works (for more in-depth tutorial see the prettyPhoto web site)
Basic Concept
The basic idea is that you download some JavaScript, CSS and Image files and write your links with a specific syntax and add a bit of JavaScript to your page and then your gallery works. What it essentially does is hijack a link you write to a large image and instead of letting the browser go to the image it grabs the image and displays it on top of the current page with a partly see through grey background between the image and the page.
NOTE: you can use more than just images in the gallery. You can use it to show video, Flash or other sites. Read the documentation for more information.
Single Image
This is a simple example of what you would do for an image (once you've included all of the other files and script tags needed) to show it in prettyPhoto.
<a href="images/theIMG.jpg" rel="prettyPhoto" title="title here" >
<img src="images/theIMG_tb.jpg" width="80" height="80" alt="Monkeys" />
</a>
Image Gallery Tutorial
- Download the files you will need. Go to this link and click on the Production Version Compressed link.
- The file is a .zip file. Unzip it.
- Copy the js, images and css folders to your site. If you already have js, images or css folders then just copy the contents of these folders to your existing folders.
- Add the following to your HTML page inside the <head> element so that it uses the css and JavaScript files you just downloaded:
<script src="js/jquery-1.3.2.min.js" type="text/javascript"></script> <link rel="stylesheet" href="css/prettyPhoto.css" type="text/css" media="screen" title="prettyPhoto main stylesheet" charset="utf-8" /> <script src="js/jquery.prettyPhoto.js" type="text/javascript" charset="utf-8"></script>
Instead of linking to a downloaded version of jQuery I would recommend linking to a CDN hosted version like below. The only thing to worry about is that a brand new version of jQuery might break the code. So test it. The version shown works.<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript" type="text/javascript"></script>
- Add this right before the closing body element on the page:
<script type="text/javascript" charset="utf-8"> $(document).ready(function(){ $("a[rel^='prettyPhoto']").prettyPhoto(); }); </script> </body>
prettyPhoto shows links to twitter and facebook by default. If you don't want them to show up the add in an options object to the prettyPhoto line,like this instead of the line that starts:$("a[rel^='prettyPhoto']").prettyPhoto({social_tools:''});
- Add your thumbnails to the page with normal HTML.
- Make sure the link in the href attribute points to the large version of the image
- Add a rel attribute to your <a> element with the following syntax rel="prettyPhoto[galleryName]"Here's a photo:
Example:<a rel="prettyPhoto[myGallery]" title="Cocoa Pod" href="large1.jpg"> <img alt="picture of cocoa pod split open" src="thumb1.jpg" /> </a> <a rel="prettyPhoto[myGallery]" title="Man with a Parro" href="large2.jpg"> <img alt="Man with a Parro" src="thumb2.jpg" /> </a> <a rel="prettyPhoto[myGallery]" title="Red Umbrella" href="large2.jpg"> <img alt="Red Umbrella" src="thumb2.jpg" /> </a>
Notice that the rel attribute is exactly the same each time. It doesn't change
You of course would just link to your own images. Remember that there are two images used. One is the thumbnail which is included with the img elment. If the user doesn't have Javascript then the big image will just show in a new page by itself.
Example Gallery
That’s all folks. Hopefully your gallery will be working shortly.
Fuente: http://www.teachingmultimedia.com/mmp240/prettyPhoto/#prettyPhoto
lunes, 13 de julio de 2015
Selecionar subconjunto de elementos de array javascript
Datos extraidos de: http://www.w3schools.com/jsref/jsref_slice_array.asp
JavaScript Array slice() Method
Example
Select elements from an array:
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1, 3);
var citrus = fruits.slice(1, 3);
The result of citrus will be:
Orange,Lemon
Try it yourself »
More "Try it Yourself" examples below.
Definition and Usage
The slice() method returns the selected elements in an array, as a new array object.
The slice() method selects the elements starting at the given start argument, and ends at, but does not include, the givenend argument.
Note: The original array will not be changed.
Browser Support
The numbers in the table specify the first browser version that fully supports the method.
Method | |||||
---|---|---|---|---|---|
slice() | 1.0 | Yes | 1.0 | Yes | Yes |
Syntax
array.slice(start,end)
Parameter Values
Parameter | Description |
---|---|
start | Required. An integer that specifies where to start the selection (The first element has an index of 0). Use negative numbers to select from the end of an array |
end | Optional. An integer that specifies where to end the selection. If omitted, all elements from the start position and to the end of the array will be selected. Use negative numbers to select from the end of an array |
Technical Details
Return Value: | A new Array, containing the selected elements |
---|---|
JavaScript Version: | 1.2 |

More Examples
Example
Select elements using negative values:
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var myBest = fruits.slice(-3, -1);
var myBest = fruits.slice(-3, -1);
The result of myBest will be:
Lemon,Apple
Try it yourself »

añadir o eliminar elementos de un array javascript
Datos extraidos de: http://www.w3schools.com/jsref/jsref_splice.asp
JavaScript Array splice() Method
Example
Add items to the array:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");
fruits.splice(2, 0, "Lemon", "Kiwi");
The result of fruits will be:
Banana,Orange,Lemon,Kiwi,Apple,Mango
Try it yourself »
More "Try it Yourself" examples below.
Definition and Usage
The splice() method adds/removes items to/from an array, and returns the removed item(s).
Note: This method changes the original array.
Browser Support
The numbers in the table specify the first browser version that fully supports the method.
Method | |||||
---|---|---|---|---|---|
splice() | 1.0 | 5.5 | 1.0 | Yes | Yes |
Syntax
array.splice(index,howmany,item1,.....,itemX)
Parameter Values
Parameter | Description |
---|---|
index | Required. An integer that specifies at what position to add/remove items, Use negative values to specify the position from the end of the array |
howmany | Required. The number of items to be removed. If set to 0, no items will be removed |
item1, ..., itemX | Optional. The new item(s) to be added to the array |
Technical Details
Return Value: | A new Array, containing the removed items (if any) |
---|---|
JavaScript Version: | 1.2 |

More Examples
Example
At position 2, add the new items, and remove 1 item:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 1, "Lemon", "Kiwi");
fruits.splice(2, 1, "Lemon", "Kiwi");
The result of fruits will be:
Banana,Orange,Lemon,Kiwi,Mango
Try it yourself »
Example
At position 2, remove 2 items:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 2);
fruits.splice(2, 2);
The result of fruits will be:
Banana,Orange
Try it yourself »

miércoles, 22 de abril de 2015
Cambiar la url del navegador sin recargar la página usando javascript o angular js
Yo lo he solucionado para angular Js que es el caso que me atañe, pero la solución pasa por javascript así que bastaría con usar la sentencia:
var objetoEstado;
window.history.pushState(objetoEstado, "titulo web", "https://jesusmgcia.blogspot.com");
Documentación oficial:
var objetoEstado;
window.history.pushState(objetoEstado, "titulo web", "https://jesusmgcia.blogspot.com");
Documentación oficial:
Manipulando el historial del navegador
El objeto DOM
window
proporciona acceso al historial del browser a través del objeto history
. Esto expone métodos útiles y propiedades que te permiten avanzar y retroceder a través del historial del usuario, asi como, --Iniciando con HTML5-- manipular el contenido del historial de la pila.Viajando a través de la historia
Retroceder y avanzar a traves del historial del usuario es realizado utilizando los métodos
back()
, forward()
, y go()
.Moviendose hacia adelante y hacia atrás
Para moverte hacia atrás, solo debes hacer:
window.history.back();
Esto actuará exactamente como si el usuario hiciera clic en el botón "atrás" en la barra de herramientas del browser.
De manera similar, puedes moverte hacia adelante (como si el usuario hiciera clic en en el botón "adelante"), de esta forma:
window.history.forward();
Moverse a un punto específico del historial
Puedes usar el método
go()
para cargar una página desde el historial de la sesión, identificada por su poscición relativa a la página actual (Iniciando con la página actual, por supuesto, relativa al índice 0).
Para moverse atráz una página (el equivalente a un llamado a
back()
):window.history.go(-1);
Para moverse una página hacia adelante, como si llamaras
forward()
:window.history.go(1);
De manera similar, puedes avanzar 2 páginas pasándo 2, y así sucesivamente.
Puedes obtener el número de páginas en el historial de la pila mirando el valor de la propiedad length:
var numberOfEntries = window.history.length;
Nota: Internet Explorer admite el paso de cadenas de URL como parámetro para
go()
; esto no es estándar y no está implementado en Gecko.Añadiendo y modificando historial de entradas
HTML5 introdujo los métodos
history.pushState()
e history.replaceState()
, los cuales te permiten añadir y modificar entradas de historial, respectivamente. Estos métodos trabajan en conjunto con el evento window.onpopstate
.Ejemplo
Suponga que http://mozilla.org/foo.html ejecuta el siguiente JavaScript:
var stateObj = { foo: "bar" };
history.pushState(stateObj, "page 2", "bar.html");
Esto causará que la barra de URL muestre http://mozilla.org/bar.html, pero no provocará que el navegador carge load.bar ni tampoco que se verifique si bar.html existe.
Suponga ahora que el usuario navega hacia http://google.com, y despúes hace clic en Atrás. En este punto, la barra de URL mostraráhttp://mozilla.org/bar.html, y la página tendrá un evento
popstate
cuyo state object contiene una copia de stateObj
. La página en si se verá como foo.html
, aunque la página podria modificar su contenido durante el evento popstate
event.
Si hacemos clic en "atrás" nuevamente, la URL cambiará a http://mozilla.org/foo.html, y el documento generará otro evento
popstate
event, esta vez con un state object nulo. Aquí también, ir atrás no cambia el contenido del documento con respecto al paso anterior, aunque el documento permite actualizar su contenido manualmente después de recibir el evento popstate
.El método pushState()
pushState()
toma tres parámetros: un objeto estado, un título (el cual es normalmente ignorado), y (opcionalmente) una URL. Vamos a examinar cada uno de estos tres parametros en más detalle:- object estado — El objeto estado es un objeto JavaScript el cual esta asociado con la nueva entrada asociada al historial creada por
pushState()
. Cada vez que el usuario navega hacia un nuevo estado, un eventopopstate
event se dispara, y la propiedadstate
del evento contiene una copia del historial de entradas del objeto estado.El objeto estado puede ser cualquier cosa que puedas pasar aJSON.stringify
. Porque Firefox guarda los objetos estado en el disco del usuario, entonces puede ser restaurado después de que el usuario reinicie su navegador, imponemos un tamaño límite de 640K caracteres en representacion JSON de un objeto estado. Si pasas un objeto estado cuya representación es más larga que esto apushState()
, el método arrojará una excepción. Si necesitas más espacio, te recomendaos usarsessionStorage
y/olocalStorage
. - título — Firefox frecuentemente ignora este parámetro, aunque podriá usarse en el futuro. Pasar una cadena de caracteres vacia aqui podría asegurar en un futuro estar a salvo en contra a futuros cambios en este método. Alternativamente podrías pasar un título corto del estado hacia el cual te estas moviendo.
- URL — El nuevo historial de entradas URL está dado por este parámetro. Note que el browser no permitirá cargar esta URL después de llamar a
pushState()
, pero podría intentar cargar la URL más tarde, por ejemplo, después de que el usuario reinicie su navegador. La nueva URL no necesita ser absoluta; si es relativ, es resuelta relativamente a la actual URL. La nueva URL debe ser del mismo origen de la actual URL; de otra forma,pushState()
no lanzará una excepción. Este parámetro es opcional; si no se especifica, se sitúa a la URL actual del documento.
En un sentido, llamar
pushState()
es similar a asignar window.location = "#foo"
,en tanto que también se va a crear y activar otra entrada al historial asociada con el documento actual. Pero pushState()
tiene las siguientes ventajas:- La nueva URL puede ser cualquier URL en el mismo origen de la actual URL. En contraste, asignar
window.location
te mantiene en el mismodocument
solamente si modificas unicamente el hash. - Tu no tienes que cambiar la URL si no deseas. En contraste, asignar
window.location = "#foo"; solamente crea una nueva entrada en el historial si el hash actual no es
#foo
. - Puedes asociar datos arbitrarios con tu nuevo historial de entrada. Con el enfoque hash-based, tu necesitas codificar todos datos relevantes dentro de una cadena de caracteres corta.
Note que
pushState()
nunca provoca un evento hashchange
para ser notificado, inclusive si la nueva URL difiere de la antigua URL únicamente en su hash.El método replaceState()
history.replaceState()
trabaja exactamente igual a history.pushState()
excepto que replaceState()
modifica la entrada al historial actual en lugar de crear una nueva.replaceState()
es particularmente útil si deseas actualizar el objeto estado o la URL del la actual entrada al historial en respuesta a alguna acción del usuario.El evento popstate
Un evento
popstate
es dirigido a la ventana cada vez que la entrada al historial cambia. Si la entrada al historial es activada y fué creada por un llamado apushState
o afectada por una llamada a replaceState
, la propiedad state del evento popstate
contiene una copia del historial de entradas del objeto estado.miércoles, 8 de abril de 2015
Capturar excepciones en Javascript
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
try {
adddlert("Welcome guest!");
}
catch(err) {
document.getElementById("demo").innerHTML = err.message;
}
</script>
</body>
</html>
Fuente: http://www.w3schools.com/js/js_errors.asp
<html>
<body>
<p id="demo"></p>
<script>
try {
adddlert("Welcome guest!");
}
catch(err) {
document.getElementById("demo").innerHTML = err.message;
}
</script>
</body>
</html>
Fuente: http://www.w3schools.com/js/js_errors.asp
Suscribirse a:
Entradas (Atom)
Jesús Moreno - Ingeniero Ténico Informático - consultor Informático
Hola, soy Jesús Moreno Ingeniero Técnico Informático en sistemas por la US y propietario de éste blog. Mi trabajo en los ultimos años se ...

-
Para aquellos que tengáis el gusanillo de la numismática, queréis empezar a coleccionar y no podéis o no queréis hacer una gran inversión en...
-
Al intentar compartir la impresora nos lanza un error que dice: " No se pudo guardar la configuración de la impresora. No hay no hay m...
-
Un método rápido y eficaz en 5 sencillos pasos: 1.- Desde SQL Management nos conectamos a nuestro servidor SQL Sercer y extraemos el met...