2015-08-09 89 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