简体   繁体   中英

How to get data from server without clicking on “submit” button?

I have this message:

<h3 id="welcomeUsername">Hello, </h3>

And I want to fire up the following script:

function pageLoaded(){

        $.get( "/getUsername", function( data ) {
            $( "#welcomeUsername" ).append( data );
            alert( "Load was performed with data: "+data );
        });

    }

It basically adds the user's name to the welcome message. But this won't fire off automatically. How do I do it and make sure the client doesn't re-direct to a new page!

The server side code:

app.get('/getUsername', function(req, res){

sess=req.session;
if(sess.username!=undefined)
{
    res.send(sess.username);
}
else
{
    res.redirect('/loginPage'); //res.sendFile(__dirname +'/public/index.html');
}

});

You should call this function when the page is loaded:

$(document).ready(function {pageLoaded();});

If you add this to your js, when the page is ready, the function will be executed.

What happens in your code, is that a function is defined, but never called. In JQuery, you can call $ with a function as an argument. If you do this, it will be loaded as soon as the HTML DOM tree is loaded. What you can do is add $(pageLoaded) at the bottom of your script, so you'd get this:

function pageLoaded(){

    $.get( "/getUsername", function( data ) {
        $( "#welcomeUsername" ).append( data );
        alert( "Load was performed with data: "+data );
    });

}
$(pageLoaded);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM