繁体   English   中英

使用JQuery AJAX将多个变量发送到Node.js服务器

[英]Send multiple variables to Node.js server with JQuery AJAX

当我尝试记录服务器接收的数据时,它显示为一个长字符串。 相反,我希望接收到的数据可以作为不同的变量分开。

客户代码

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.');
}
});

}

服务器代码

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); 应该显示值“ TEST”。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM