Menú

Mostrar Mensajes

Esta sección te permite ver todos los mensajes escritos por este usuario. Ten en cuenta que sólo puedes ver los mensajes escritos en zonas a las que tienes acceso en este momento.

Mostrar Mensajes Menú

Temas - Xargam

#1
Desarrollo Web / [AUXILIO] Insertar string JSON
26 Septiembre 2019, 04:06 AM
Este código me está enloqueciendo:

Código (javascript,26) [Seleccionar]
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
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($filefilesize("./images/photo_index.txt")));
    
fwrite($filestrval(++$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?
#3
Si guardo varios punteros a estructura reservados con malloc en un archivo de texto o binarios, debo liberar esos punteros?
#4
Hola comunidad tengo dificultades con las funciones al retornar un puntero a char o asignandolos a un doble puntero pasado por parametro. ¿Si uno declara una cadena en una funcion y quiere llevarla a main, si un puntero toma esa cadena se desapila igual?
#5
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....
#6
Buen dia comunidad! Estoy tratando de imprimir un numero LONG DOUBLE pero ningun especificador lo hace. Probe con "%LF" y "%Lf" pero no hay caso... Alguno sabe cual es?
#7
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);
   free(movies);
   return 0;
}


int x(eMovie* movie)
{
   int salir = 0;
   int moves = 0;
   while(salir != 27)
   {
       printf("\nTITULO: ");
       scanf("%s", (movie + moves)->titulo);
       printf("\nDURACION: ");
       scanf("%d", &(movie + moves)->duracion);
       printf("SALIR? esc:");
       salir = getche();
       if(salir != 27)
       {
           moves++;
           movie =(eMovie*) realloc(movie,sizeof(eMovie)*(moves+1) );
       }
   }
   free(movie);
   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
//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
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?
#10
Necesito saber el rango de una variable de tipo float. Alguien como traducir esa notacion a un numero comun y corriente?
#11
Hola gente, estoy haciendo una funcion que pide string (caracteres limitados). Tengo una funcion en la que al scanf le asigne %[^\n] para que tome los espacios del string. Tambien quiero tener otra funcion que pida string hasta que encuentre un espacio, por lo que cambie la mascara por %s. Encontre un problema grave en esta segunda funcion:


void getRangedSimStr(char* vec,char message[],char eMessage[],int minChars, int maxChars)
{
    char palabra[1000];
    printf("%s", message);
    setbuf(stdin,NULL);
    scanf("%s",palabra);
    setbuf(stdin,NULL);
    while(strlen(palabra) > maxChars || strlen(palabra) < minChars)
    {
        printf("%s",eMessage);
        scanf("%s",palabra);
        setbuf(stdin,NULL);
    }
    strcpy(vec,  palabra);
}


Al momento de ser ejecutada en un bucle for de 3 iteraciones y guardado el string en una matriz con este codigo:


    char matriz[CANT][CHARS];
    char primeraLetra;
    for(int i = 0; i< CANT; i++)
    {
        printf("Ingrese nombre %d: ",i+1);
        getRangedSimStr(matriz[i],"","Nombre invalido, reingrese: ",1,49);
        strlwr(matriz[i]);
        primeraLetra = matriz[i][0];
        primeraLetra = toupper(primeraLetra);
        matriz[i][0] = primeraLetra;

    }
    for(int i = 0; i < CANT; i++)
    {
        printf("%s\n",matriz[i]);
    }


Si yo escribo "SPORE ES BUENO" el bucle for no me pide la segunda y la tercera vez que ingrese string. Muestra la matriz con SPORE en indice 0, ES en el indice 1 y BUENO en el indice 2.
Miren: