简体   繁体   中英

error: send data from html page to server and receive some data from server

when i run this code i am unable to send and receive data .I request to correct my code This is server side code

 var http = require("http") ; var fs = require("fs") ; http.createServer(function(req,res){ if(req.url == '/'){ fs.readFile('post.html',function(err,data){ res.writeHead(200, {'Content-Type': 'text/html','Content-Length':data.length}); res.write(data); res.end(); }); } else if (req.url == '/dat') { req.on('data', function (data){ console.log(data.toString()); console.log("yo"); }); console.log("second"); res.writeHead(200, {'Content-Type': 'text/plain'}); res.write("Hi, Server is still alive and awaiting your orders Dear User :)"); res.end() ; } else{ console.log("third"); } }).listen(2000); 

this is client side code

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $.post("http://localhost:2000/dat"),
        JSON.stringify({
          name: "Donald Duck",
          city: "Duckburg"
        }),
        function(data,status){
            alert("Data: " + data + "\nStatus: " + status);
        }

    });
});
</script>
</head>
<body>

<button>Send an HTTP POST request to a page and get the result back</button>
</body>
</html>

i kept these two codes in same folder and tried to compile. i was successfully ran this code but after doing some minor changes to code . code stopped working and i was unable to undo that .I need corrected code of mine if possible .

You jQuery code should be written like this.

$("button").click(function() {
  $.post(
    "http://localhost:2000/dat",
    JSON.stringify({
      name: "Donald Duck",
      city: "Duckburg"
    }),
    function(data, status) {
      alert("Data: " + data + "\nStatus: " + status);
    }
  );
});

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