elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Curso de javascript por TickTack


  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:

Código
  1. function mostrar(jsonStr : string) {
  2.    console.log(typeof jsonStr );
  3.    console.log(jsonStr);
  4.    let jsonObj = JSON.parse(jsonStr );
  5.    alert(`Id: ${jsonObj.Id} - Marca: ${jsonObj.Marca} -  Precio: ${jsonObj.Precio} -  Color: ${jsonObj.Color} - \
  6.    Modelo: ${jsonObj.Modelo}.`);
  7. }
  8. function leer() {
  9.    let tabla = "<table border='1'><thead><th>Id</th><th>Marca</th><th>Precio</th><th>Color</th><th>Modelo</th>\
  10.    <th>Action</th></thead><tbody>";
  11.    let xhttp = new XMLHttpRequest();
  12.    xhttp.onreadystatechange = () => {
  13.        if( xhttp.readyState == 4 && xhttp.status == 200) {
  14.            let jsonObj = JSON.parse(xhttp.responseText);
  15.            for(let i = 0 ; i < jsonObj.length ; i++) {
  16.                let g  = JSON.stringify(jsonObj[i]);
  17.                console.log(typeof g);
  18.                console.log(g);
  19.                tabla += "<tr>";
  20.                tabla += `<td>${jsonObj[i].Id}</td>`;
  21.                tabla += `<td>${jsonObj[i].Marca}</td>`;
  22.                tabla += `<td>${jsonObj[i].Precio}</td>`;
  23.                tabla += `<td>${jsonObj[i].Color}</td>`;
  24.                tabla += `<td>${jsonObj[i].Modelo}</td>`;
  25.                console.log(JSON.stringify(jsonObj[i]));
  26.                tabla += "<td><input type='button' value='ver' onclick=\"mostrar(\'"+JSON.stringify +"\')\"</td>"; // AQUI
  27.                tabla += "</tr>";
  28.            }
  29.            tabla += "</tbody></table>";
  30.            (<HTMLDivElement>document.getElementById("result")).innerHTML += tabla;
  31.        }
  32.    }
  33.    xhttp.open("GET", "./json_test.php", true);
  34.    xhttp.send();
  35. }
  36.  

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:
Código:
<!--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?
3  Programación / Programación C/C++ / [ANSI C] Si guardo punteros dinamicos en un archivo ¿Debo hacer free? en: 25 Junio 2018, 10:10 am
Si guardo varios punteros a estructura reservados con malloc en un archivo de texto o binarios, debo liberar esos punteros?
4  Programación / Programación C/C++ / Retornar punteros char? ¿Si o si memoria dinamica? en: 23 Junio 2018, 22:00 pm
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  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....
6  Programación / Programación C/C++ / ¿Cual es el especificador de formato para LONG DOUBLE? Ansi C en: 8 Junio 2018, 21:56 pm
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  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:


Código
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <conio.h>
  4. #define MOVFILE "movies.bin"
  5.  
  6.  
  7. typedef struct
  8. {
  9.    char titulo[50];
  10.    int duracion;
  11.  
  12. } eMovie ;
  13.  
  14. int x(eMovie* movie);
  15. void y(eMovie* movie, int tam);
  16.  
  17. int main()
  18. {
  19.  
  20.    eMovie* movies = (eMovie*) malloc(sizeof(eMovie));
  21.    int index = x(movies);
  22.    index++;
  23.    y(movies,index);
  24.    free(movies);
  25.    return 0;
  26. }
  27.  
  28.  
  29. int x(eMovie* movie)
  30. {
  31.    int salir = 0;
  32.    int moves = 0;
  33.    while(salir != 27)
  34.    {
  35.        printf("\nTITULO: ");
  36.        scanf("%s", (movie + moves)->titulo);
  37.        printf("\nDURACION: ");
  38.        scanf("%d", &(movie + moves)->duracion);
  39.        printf("SALIR? esc:");
  40.        salir = getche();
  41.        if(salir != 27)
  42.        {
  43.            moves++;
  44.            movie =(eMovie*) realloc(movie,sizeof(eMovie)*(moves+1) );
  45.        }
  46.    }
  47.    free(movie);
  48.    return moves;
  49. }
  50.  
  51. void y(eMovie* movie, int tam)
  52. {
  53.    for(int i = 0; i < tam; i++)
  54.    {
  55.        printf("\n\nTITULO: %s\n", (movie + i)->titulo);
  56.        printf("DURACION: %d\n", (movie + i)->duracion);
  57.    }
  58. }
  59.  

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?
10  Programación / Programación C/C++ / ¿Que numero exactamente es 3.4E+-38? en: 19 Abril 2018, 22:23 pm
Necesito saber el rango de una variable de tipo float. Alguien como traducir esa notacion a un numero comun y corriente?
Páginas: [1] 2
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines