简体   繁体   English

错误:将数据从html页面发送到服务器,并从服务器接收一些数据

[英]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. 您的jQuery代码应这样编写。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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