[英]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.