简体   繁体   中英

Elegant way to send form data to node.js - node-static

I try to send some data to my node.js / node-static app and store it in a file.

Right now i use a basic html form and capture the pathfile:

Server side:

var daten = url_parts.query;
if (pathfile== '/get.htm'){           // get.htm just redirects back to form
        console.log('Device 1:', daten);
        fs.writeFile("devices.txt", devices(daten), function(err) {
            if(err) {console.log(err);} else {console.log("The file was saved!");}
            }); 
        }

I feel dirty using this but i am a bit overwhelmed by the possibilities to perform such a simple task.

Using jQuery seems the way to go.

My problem: How can I send the data without a page refresh or redirecting to another page? What is the elegant way? Where do I perform the 'magic'? Client or Server side?

I ended up restructuring server and client side. Maybe someone finds this useful or can improve this suggestion:

Server:

      if (pathfile== '/get.json'){
    fs.writeFile("devices.txt", devices(daten), function(err) {
        if(err) {console.log(err);} else {console.log("The file was saved!");}
        }); 
    response.writeHead(200, { "Content-type": "application/json" });        
    response.end();
    return;
    }

Client:

$('#enter').click(function(){                           
    var data =  $('form').serialize() ;                 
    $.ajax({        
        type: "get",
        url: "get.json",                                            
        data: data,
        success: function(){alert('data was send!');},
        error: function(){alert('server not responding!');}
    });
return false;                                       
}); 

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