【发布时间】:2016-09-16 00:43:26
【问题描述】:
我想从客户端发送命令到服务器示例更改图像 url 或标签文本。我已经设法使服务器和客户端之间的连接正常工作,并且按钮单击工作,但我无法从 index.js 文件中操作 DOM。有没有可靠的方法来做到这一点?我的客户端使用 PHP 从 mySQL 数据库获取数据,我想将该数据作为数组传递给服务器并呈现给视图。到目前为止,这是我的代码:
服务器:index.js -
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get("/",function(req,res){
res.sendFile(__dirname + '/index.html');
app.use(express.static(__dirname));
});
//This is auto initiated event when Client connects to Your Machien.
io.on('connection', function(client) {
console.log('Client connected...');
client.on('test',function(msg){
console.log("i can see this in cmd console");
// i would like to do like this but it says "document is not defined"
//document.getElementById("mediaContainer").innerHTML = "Paragraph changed!";
});
});
http.listen(3000,function(){
console.log("Listening on 3000");
});
客户端:app.js -
$(document).ready(function () {
$("#button1").click(function(){
socket.emit('test',$("#someinput").val());
});
});
我希望它像这样工作: 服务器:app.js -
$(document).ready(function () {
var socket = io.connect('http://192.168.2.65:3000');
socket.on('test',function(msg){
$("#mediaContainer").append(msg);
console.log("i cant get this to work");
});
});
谢谢:)
【问题讨论】:
标签: javascript jquery node.js socket.io