簡體   English   中英

錯誤:將數據從html頁面發送到服務器,並從服務器接收一些數據

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

當我運行此代碼時,我無法發送和接收數據。我要求更正我的代碼, 這是服務器端代碼

 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); 

這是客戶端代碼

<!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>

我將這兩個代碼保存在同一文件夾中並嘗試進行編譯。 我成功運行了此代碼,但是對代碼做了一些小的更改。 代碼停止工作,我無法撤消該操作。如果可能,我需要更正我的代碼。

您的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