2016-12-04 94 views
0

接收的一些数据,当我运行这段代码我无法发送和接收数据。我要求改正我的代码 这是服务器端代码 错误:从HTML页面数据发送到服务器和从服务器

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> 

我将这两个代码保存在同一个文件夹中,并试图编译。我成功地运行了这段代码,但是在对代码做了一些小修改之后。代码停止工作 ,我无法撤消该操作。如果可能,我需要更正我的代码。

+0

实际上你需要什么作为回应?你现在得到什么? –

回答

0

你应该这样写jQuery代码。

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