javascript 获取 Node.js 以从 HTML 文本字段获取用户输入?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20397306/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 18:24:38  来源:igfitidea点击:

Get Node.js to get user's input from a HTML text field?

javascriptajaxnode.js

提问by Mike

I've basically been trying to make a simple game where the user can submit their high-score to a Node.js server. I'm just trying to do something very simple but can't seem to find much to help me online!

我基本上一直在尝试制作一个简单的游戏,用户可以将他们的高分提交给 Node.js 服务器。我只是想做一些非常简单的事情,但似乎无法在网上找到很多帮助我的东西!

At the moment I've got the main page to connect and respond to the server using AJAX.

目前我已经有了使用 AJAX 连接和响应服务器的主页。

Here's the HTML:

这是 HTML:

<div id="test"></div> 
<h3>Upload your high-score:</h3>
Your score: <input type="text" name="yourScore">
<button id="SubmitBtn" type="submit">Submit</button>

Here's the JavaScript which triggers when the "Submit" button is clicked and appends the "test" div when successfully connected (Just to show it responds):

这是在单击“提交”按钮时触发的 JavaScript,并在成功连接时附加“测试”div(只是为了显示它的响应):

<script> 
$(document).ready(function() {
$('#SubmitBtn').click(function (event) {
    $.ajax({ 
        url: 'http://localhost', 
        dataType: "jsonp", 
        jsonpCallback: "_testcb", 
        cache: false, 
        timeout: 5000, 
        success: function(data) { 
            $("#test").append(data); 
        }, 
        error: function(jqXHR, textStatus, errorThrown) { 
            alert('Error connecting to the Node.js server... ' + textStatus + " " + errorThrown); 
        } 
    }); 
});

});

});

And here's my Node.js at the moment where it runs and responds:

这是我的 Node.js 运行和响应的时刻:

var http = require('http'); 
console.log('Game server running...'); 
http.createServer(function (req, res) { 
console.log('Submit button has been clicked.'); 
res.writeHead(200, {'Content-Type': 'text/plain'}); 
res.end('_testcb(\'{"message": "Welcome! Node.js Responding!"}\')'); 
}).listen(80); 

So yeah, if anyone knows how I can get my Node.js server to read the data in the "yourScore" text field and when the "SubmitBtn" button has been clicked to send the data to the server, I would be most thankful!

所以是的,如果有人知道我如何让我的 Node.js 服务器读取“yourScore”文本字段中的数据,并且当“SubmitBtn”按钮被点击将数据发送到服务器时,我会非常感激!

回答by letiagoalves

First

第一的

You are not sending any data with your AJAX request.

您没有通过 AJAX 请求发送任何数据。

Possible solution (it is better if you get score inputelement using an IDor serializing the formelement):

可能的解决方案(最好input使用 anID或序列化form元素获取 score元素):

$.ajax({ 
    url: 'http://localhost',
    data: { score : $("input[name='score']").val() },
    dataType: "jsonp", 
    jsonpCallback: "_testcb", 
    cache: false, 
    timeout: 5000, 
    success: function(data) { 
        $("#test").append(data); 
    }, 
    error: function(jqXHR, textStatus, errorThrown) { 
        alert('Error connecting to the Node.js server... ' + textStatus + " " + errorThrown); 
    } 
});

Second

第二

Inside your NodeJS request handler you can get the sent data using the request object.

在 NodeJS 请求处理程序中,您可以使用请求对象获取发送的数据。

Possible solution:

可能的解决方案:

var http = require('http'); 
http.createServer(function (req, res) {
      var score = req.body.score;
      console.log(score);
      //do whatever you want
      res.writeHead(200, {'Content-Type': 'text/plain'}); 
      res.end('_testcb(\'{"message": "Welcome! Node.js Responding!"}\')'); 
}).listen(80); 

回答by roo2

You need to send a POST to the server, check out this simple example

您需要向服务器发送 POST,请查看此简单示例

in your script:

在你的脚本中:

$.ajax({
    type: "POST",
    data: {
        yourScore: $('input[name="yourScore"]').val()
    }, 
    //other parameters

and in your server

并在您的服务器中

http.createServer(
   //...
   if (req.method == 'POST'){
      console.log(req.body.yourScore)