Javascript onLoad does not load

1

I have this Javascript function inside my HTML.

$("#aviso1").on('click', function (e) {
        // Initialize the object, before adding data to it.
        //  { } is declarative shorthand for new Object()
        var obj = {};
        obj.titulo = $("#Titulo").val();
        obj.informacion = $("#Informacion").val();

        //In order to proper pass a json string, you have to use function JSON.stringfy
        var jsonData = JSON.stringify(obj);

        $.ajax({
            url: 'Titulo.ashx?Num=1',
            type: 'POST',
            data: jsonData,
            success: function (data) { document.getElementById("Titulo1").innerHTML = data; },
            error: function (errorText) { alert("Whoops something went wrong!"); }
        });
        e.preventDefault();
    });

But if I put it on ('click' ... if it displays the information, but when I put it on ('load' ... it does not load the information.

What is owed and how can I solve it?

EDIT: To be able to use the functions in this way so that they load automatically instead of typing

on('load' function(e) ... 

or

on('click' function(e) ...

must be

ready(function(e) ...
    
asked by CarlosOro 23.05.2016 в 20:56
source

2 answers

1

The load event only applies to the DOM root object which means that on a page you can apply it only to the window object or the document. In any other element it will not be generated:

load Event Reference

If you use jQuery (as I see) and you want the function that you have now associated with the click event to be executed when loading the page, you would have nothing else to do:

$(function() {
        // Initialize the object, before adding data to it.
        //  { } is declarative shorthand for new Object()
        var obj = {};
        obj.titulo = $("#Titulo").val();
        obj.informacion = $("#Informacion").val();

        //In order to proper pass a json string, you have to use function JSON.stringfy
        var jsonData = JSON.stringify(obj);

        $.ajax({
            url: 'Titulo.ashx?Num=1',
            type: 'POST',
            data: jsonData,
            success: function (data) { document.getElementById("Titulo1").innerHTML = data; },
            error: function (errorText) { alert("Whoops something went wrong!"); }
        });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Titulo">Título</div>
<div id="Informacion">Información</div>
<div id="Titulo1"></div>

With the syntax:

$(function(){...});

jQuery executes the function once the loading of the page has completed.

    
answered by 23.05.2016 / 21:01
source
1

So ... For the functions to load me without the need to click, I must change to:

$("#aviso1").ready(function (e) { ...
    
answered by 23.05.2016 в 21:14