|
Mostrar Temas
|
Páginas: [1] 2
|
1
|
Programación / Desarrollo Web / [AUXILIO] Insertar string JSON
|
en: 26 Septiembre 2019, 04:06 am
|
Este código me está enloqueciendo: function mostrar(jsonStr : string) { console.log(typeof jsonStr ); console.log(jsonStr); let jsonObj = JSON.parse(jsonStr ); alert(`Id: ${jsonObj.Id} - Marca: ${jsonObj.Marca} - Precio: ${jsonObj.Precio} - Color: ${jsonObj.Color} - \ Modelo: ${jsonObj.Modelo}.`); } function leer() { let tabla = "<table border='1'><thead><th>Id</th><th>Marca</th><th>Precio</th><th>Color</th><th>Modelo</th>\ <th>Action</th></thead><tbody>"; let xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = () => { if( xhttp.readyState == 4 && xhttp.status == 200) { let jsonObj = JSON.parse(xhttp.responseText); for(let i = 0 ; i < jsonObj.length ; i++) { let g = JSON.stringify(jsonObj[i]); console.log(typeof g); console.log(g); tabla += "<tr>"; tabla += `<td>${jsonObj[i].Id}</td>`; tabla += `<td>${jsonObj[i].Marca}</td>`; tabla += `<td>${jsonObj[i].Precio}</td>`; tabla += `<td>${jsonObj[i].Color}</td>`; tabla += `<td>${jsonObj[i].Modelo}</td>`; console.log(JSON.stringify(jsonObj[i])); tabla += "<td><input type='button' value='ver' onclick=\"mostrar(\'"+JSON.stringify +"\')\"</td>"; // AQUI tabla += "</tr>"; } tabla += "</tbody></table>"; (<HTMLDivElement>document.getElementById("result")).innerHTML += tabla; } } xhttp.open("GET", "./json_test.php", true); xhttp.send(); }
Donde esta el aquí no hay manera de que me reconozca las comillas que rodean al parametro de la funcion mostrar ( Que es un objeto json convertido a string). Probé de mil maneras y si consigo que funcione lo hace con comportamientos extraños. En la funcion mostrar en vez de recibir un string recibo un object. Evidentemente por la falta de las comillas que rodean el parametro. Ayuda por fa.
|
|
|
2
|
Programación / PHP / Realizar un echo e ir concatenando en un documento html[RESUELTO]
|
en: 15 Septiembre 2019, 06:24 am
|
Hola comunidad elhacker.net mi problema es respecto a este codigo: <!--Aplicación Nº 41 (Galería de Imágenes) Amplíe el ejercicio de la galería de fotos realizada anteriormente y permita al usuario añadir nuevas fotos. Para ello hay que poner el atributo enc_type=”multipart/form-data” en el FORM y usar la variable $_FILES['foto'].--> <?php /* Leo el numero con el que se guardara el archivo y guardo el numero para el siguiente*/ if (isset($_FILES["foto"]["name"])) { $file = fopen("./images/photo_index.txt", "r+"); $photoNum = intval(fread($file, filesize("./images/photo_index.txt"))); fwrite($file, strval(++$photoNum)); fclose($file);
$path = "./images/foto$photoNum." . pathinfo($_FILES["foto"]["name"], PATHINFO_EXTENSION); move_uploaded_file($_FILES["foto"]["tmp_name"], $path); $tabla = "<tr><td><img src='$path' width='100px' height='100px'></td><td>" . $_POST["descripcion"] . "</tr>"; } ?> <!DOCTYPE html> <html lang="es">
<head> <script type="text/javascript" src="./javascript/functions.js"></script> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Imagenes</title> </head>
<body> <form method="POST" enctype="multipart/form-data" action="index.php"> <fieldset style="width:15em;"> <legend>Agregar nuevas fotos al servidor</legend> Foto: <input type="file" name="foto" accept="image/jpg,jpeg"><br /> Descripción: <input type="text" name="descripcion" style="width:20em"><br /> <input type="submit" value="Enviar" > </fieldset> </form> <table border="1"> <thead> <th>Fotos</th> <th>Descripción</th> </thead> <tbody id="1"> <tr> <td><a href="./original.html"><img src="./images/paisaje1.jpg" width="100px" height="100px" onclick="saveSelectedImg(this)"></a> </td> <td>Bosque mágico</td> </tr> <tr> <td><a href="./original.html"><img src="./images/paisaje2.jpg" width="100px" height="100px" onclick="saveSelectedImg(this)"></a></td> <td>Cataratas</td> </tr> <tr> <td><a href="./original.html"><img src="./images/paisaje3.jpg" width="100px" height="100px" onclick="saveSelectedImg(this)"></a></td> <td>Playa montañosa</td> </tr> <tr> <td><a href="./original.html"><img src="./images/paisaje4.jpg" width="100px" height="100px" onclick="saveSelectedImg(this)"></a></td> <td>Cascadas</td> </tr> <tr> <td><a href="./original.html"><img src="./images/paisaje5.jpg" width="100px" height="100px" onclick="saveSelectedImg(this)"></a></td> <td>Pradera</td> </tr> <tr> <td><a href="./original.html"><img src="./images/paisaje6.jpg" width="100px" height="100px" onclick="saveSelectedImg(this)"></a></td> <td>Pradera otoñal</td> </tr> <tr> <td><a href="./original.html"><img src="./images/paisaje7.jpg" width="100px" height="100px" onclick="saveSelectedImg(this)"></a></td> <td>Río y cascadas</td> </tr> <tr> <td><a href="./original.html"><img src="./images/paisaje8.jpg" width="100px" height="100px" onclick="saveSelectedImg(this)"></a></td> <td>Playa mágica</td> </tr> <tr> <td><a href="./original.html"><img src="./images/paisaje9.jpg" width="100px" height="100px" onclick="saveSelectedImg(this)"></a></td> <td>Perú</td> </tr> <tr> <td><a href="./original.html"><img src="./images/paisaje10.jpg" width="100px" height="100px" onclick="saveSelectedImg(this)"></a></td> <td>Bosque de otoño</td> </tr> <?php if(isset($_FILES["foto"]) ){ echo $tabla; } ?> </tbody> </thead> </table> </body>
</html> Es un formulario que genera una tabla con imágenes. La parte que me esta complicando es el echo de $tabla que se hace abajo. La idea es que a medida que el usuario cargue fotos ese echo vaya 'concatenando' filas . El problema es que a medida que cargo fotos se van sustituyendo en vez de concatenarse. ¿Como puedo hacer para que el echo vaya concantenando nuevo codigo html?
|
|
|
5
|
Seguridad Informática / Seguridad / ¿Podria instalar varios antivirus y tener activado uno ?
|
en: 22 Junio 2018, 16:05 pm
|
Muchas veces algunos antivirus detectan ciertos virus que otros no... En toda la red dicen que al funcionar 2 antivirus en simultaneo la pc puede dejar de funcionar debido a que estos se combaten... pero si tengo 20 antivirus en la maquina y solo activo uno. En caso de que mi pc se vuelva lenta y el antivirus que tengo activado no pueda solucionarlo, hago analisis con los demas siempre activando solo uno...No creo que algun virus pueda escapar a tal cantidad de antivirus....
|
|
|
7
|
Programación / Programación C/C++ / Problema con realloc funciones y punteros a estructuras [RESUELTO]
|
en: 2 Junio 2018, 06:26 am
|
Hola gente estoy volviendome loco con realloc.... Veo que corrompe datos.. Declare una estructura, luego cree un puntero dinamico a ella con malloc. El problema es que si yo paso el puntero a una funcion y en la funcion hago realloc del puntero los datos se corrompen.... por que???????????? Por que si uso realloc con un dato que no es de la funcion mi programa funciona mal¨??? Ejemplo: #include <stdio.h> #include <stdlib.h> #include <conio.h> #define MOVFILE "movies.bin" typedef struct { char titulo[50]; int duracion; } eMovie ; int x(eMovie* movie); void y(eMovie* movie, int tam); int main() { eMovie * movies = (eMovie *) malloc(sizeof(eMovie )); int index = x(movies); index++; y(movies,index); return 0; } int x(eMovie* movie) { int salir = 0; int moves = 0; while(salir != 27) { scanf("%s", (movie + moves )->titulo ); scanf("%d", &(movie + moves )->duracion ); salir = getche(); if(salir != 27) { moves++; movie =(eMovie *) realloc(movie ,sizeof(eMovie )*(moves +1) ); } } return moves; } void y(eMovie* movie, int tam) { for(int i = 0; i < tam; i++) { printf("\n\nTITULO: %s\n", (movie + i )->titulo ); printf("DURACION: %d\n", (movie + i )->duracion ); } }
Como ven el puntero a movie se pasa a una funcion y alli se hace el realloc pruebenlo, el string se cambia... Al imprimirse...
|
|
|
8
|
Programación / Programación C/C++ / Terrible problema al trabajar con punteros, estructura, memoria dinam y archivo!
|
en: 1 Junio 2018, 18:26 pm
|
//El problema fue solucionado!!!! ya l oencontre era la variable moves Hola gente estoy haciendo un codigo que reserva memoria dinamica y guarda la direccion del primer elemento en un puntero a estructura. Luego se abre o genera un archivo. Cargo un dato al puntero y lo escribo en el archivo. El archivo se genera correctamente pero al cargar el dato al puntero , este se guarda en MAIN pero por alguna razon extraña al entrar a una funcion para gaurdar datos en archivo LOS DATOS DEL PUNTERO SE CONVIERTEN EN BASURA. Miren les muestro el codigo a ver si alguien descubre el error:
//DECLARACIONES
typedef struct {
char title[50]; int duracion;
} eMovies;
//MAIN
int quantity = 1; int value; int moves = 0; eMovies* movies; movies = newMovie(); // FUNCION 1 if( movies == NULL) { printf("ERROR INICIAL"); system("pause"); exit(1); } value = loadMovies(movies,&quantity,"movies.bin"); //FUNCION 2 if( !value ) { printf("ERROR"); system("pause"); exit(1); } while(moves < quantity) { printf("El titulo es %d y la duracion es %s\n\n", (movies + moves)->duracion,(movies + moves)->title ); //imprimo la basura de la estructura system("pause"); moves++; }
printf("quantity es %d\n\n",quantity); //MUESTRO LA VARIABLE system("pause"); printf("Ingrese titulo: "); scanf("%s", (movies + moves)->title ); //SUSTITUYO LA BASURA POR UN STRING setbuf(stdin, NULL); printf("\nIngrese duracion: "); scanf("%d", &(movies + moves)->duracion ); //SUSTITUYO LA BASURA POR UN INT setbuf(stdin, NULL); printf("%s", (movies + moves)->title); //EL STRING GUARDAO SE VE CORRECTAMEN printf("%p",movies); //LA DIRECCION SE IMPRIME llamenla 0f455f printf("Datos cargados en la estructura.\n"); system("pause");
saveMovies(movies,"movies.bin"); //FUNCION 3 ERROR ALLI free(movies);
return 0;
------------------------
FUNCION 1
eMovies* newMovie(void) { eMovies* movie; movie = malloc(sizeof(eMovies)); return movie; }
FUNCION 2
int loadMovies(eMovies* movies, int* quantity , char* filename) { FILE* file; eMovies* aux; int verify = 1; int moves = 0; int writed;
file = fopen(filename,"rb"); if(file == NULL) { file = fopen(filename, "wb"); if(file == NULL ) { verify = 0; } } else { while( !feof(file) ) { writed = fread(movies + moves,sizeof(eMovies),1,file ); if(writed != 1) { if( feof(file) ) { break; } else { verify = 0; break; } }
moves++; if( moves >= *quantity ) { aux =(eMovies*) realloc(movies,sizeof(eMovies)*(moves+1) ); if(aux == NULL) { verify = 0; break; } movies = aux; *quantity = moves+1; } }
} fclose(file); return verify; }
FUNCION 3 LA PROBLEMATICA
int saveMovies(eMovies* movies, char* filename) { int verify = 1; int moves = 0; int readings; FILE* file; printf("\nDireccion de memoria de title: %p\n", movies->title); //LA DIRECCION IMPRESA ES LA MISMA DEL MAIN, ESO ES CORRECTO
printf("\n %s", movies, (movies)->title ); //SE MUESTRA BASURA... EL DATO CARGADO EN EL MAIN YA NO ESTA OSEA WTF!!!! scanf("%s", movies->title ); printf("\ndir %p, %s", movies, (movies)->title ); //MAS BASURA system("pause"); file = fopen(filename,"wb"); if(file == NULL) { verify = 0; } else { while( !feof(file) ) { readings = fwrite(movies + moves,sizeof(eMovies),1,file); //ESCRIBE BASURA Y SE CUELGA EL PROGRAMA......... if(readings != 1) { if( feof(file) ) { break; } else { verify = 0; break; } } moves++; } } fclose(file); return verify;
}
|
|
|
9
|
Programación / Programación C/C++ / Numero flotante mas pequeño... ¿Quien lo conoce?
|
en: 6 Mayo 2018, 03:27 am
|
Estoy haciendo funciones que validan que el usuario no se pase de los rangos correspondientes a cada tipo de dato. No puedo encontrar exactamente el numero minimo de un flotante en ningun lado... Se que existe la constante FLT_MIN que lo guarda, pero cuando uso un printf para imprimirlo en la consola y copiarlo solo se muestran ceros. El numero maximo si pude copiarlo de la constante FLT_MAX... ¿Alguien sabe como conseguirlo al minimo?
|
|
|
|
|
|
|