我基本上一直试图制作一个简单的游戏,用户可以将其高分提交给Node.js服务器。我只是想做一些非常简单的事情,但似乎找不到太多帮助我在线!
目前我已经有了主页连接并使用AJAX响应服务器。
这是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>
这是在单击“提交”按钮时触发的JavaScript,并在成功连接时附加“test”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);
}
});
});
});
这是我的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);
所以是的,如果有人知道如何让我的Node.js服务器读取“yourScore”文本字段中的数据,并且当点击“SubmitBtn”按钮将数据发送到服务器时,我会非常感谢!
答案 0 :(得分:1)
您没有使用您的AJAX请求发送任何数据。
可能的解决方案(如果您使用input
获取得分ID
元素或序列化form
元素,则会更好:
$.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);
}
});
在NodeJS请求处理程序中,您可以使用请求对象获取发送的数据。
可能的解决方案:
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);
答案 1 :(得分:0)
您需要向服务器发送POST,请查看this simple example
在你的脚本中:
$.ajax({
type: "POST",
data: {
yourScore: $('input[name="yourScore"]').val()
},
//other parameters
并在您的服务器中
http.createServer(
//...
if (req.method == 'POST'){
console.log(req.body.yourScore)