2015-08-09 86 views
0

当我尝试记录服务器收到的数据时,它显示为一个长字符串。相反,我希望收到的数据可以分为不同的变量。使用JQuery AJAX发送多个变量到Node.js服务器

客户端代码

function sendData() { 

var datas = { testdata: "TEST", testdata2: "TEST2" }; 

$.ajax({ 
url: 'server', 
data: JSON.stringify(datas), 
type: 'POST', 

success: function (data) { 

    $('#lblResponse').html(data); 
}, 
error: function (xhr, status, error) { 
    console.log('Error: ' + error.message); 
    $('#lblResponse').html('Error connecting to the server.'); 
} 
}); 

} 

Server代码

var http = require('http'); 
http.createServer(function (req, res) { 

    console.log('Request received'); 

    res.writeHead(200, { 
     'Content-Type': 'text/plain', 
     'Access-Control-Allow-Origin': '*' 
    }); 
    req.on('data', function (chunk) { 
     console.log('GOT DATA!'); 

     var receivedData = JSON.parse(chunk); 

     console.log(receivedData); 
    }); 

    res.end("hello"); 

}).listen(1337); 

我想能够调用单个变量获得服务器从它的价值。例如console.log(testdata);应显示值“测试”。

回答

0

通过字符串化你的数据对象,你发送一个字符串到服务器作为请求正文,它可能使用“application/x-www-form-urlencoded”编码进行编码。

  1. 你可能不应该JSON.stringify(datas),只是使用datas
  2. 您需要解析服务器上的请求正文。为此,您可以使用模块,如body