简体   繁体   English

客户端javascript与服务器node.js通信的简单方法

[英]Simple method of client javascript communicating with server node.js

My objective is to design a small site with auto-completion of a field which would take suggestions from server's database (Node.js + MySQL). 我的目标是设计一个自动完成字段的小型站点,该站点将从服务器数据库(Node.js + MySQL)中获取建议。

What methods I could use to achieve this client-server communication as user types value into a field. 当用户将值输入字段时,我可以使用哪些方法来实现客户端-服务器通信。 I am looking for something greater than writing own AJAX requests, but easier than frameworks like Angular. 我正在寻找比编写自己的AJAX请求更大的东西,但比Angular等框架更容易。

I use the same NodeJS + MySQL setup. 我使用相同的NodeJS + MySQL设置。

If you already have your app going, I suggest installing socket.io . 如果您已经开始使用应用程序,则建议安装socket.io Otherwise, look into Express.IO which is a framework for NodeJS development with Socket.IO integrated into it. 否则,请查看Express.IO ,它是集成了Socket.IO的NodeJS开发框架。

Websockets make AJAX look silly! Websocket使AJAX看起来很傻!

In NodeJS, you listen for io.emit("someEvent", {object-data-here}); io.emit("someEvent", {object-data-here}); ,您监听io.emit("someEvent", {object-data-here}); on the client side, and route it on the server side with app.io.route("someEvent", function(request,response) {}); 在客户端,并通过app.io.route("someEvent", function(request,response) {});在服务器端进行app.io.route("someEvent", function(request,response) {});

Don't copy and paste this, but firing a socket for a keyUp event is easy peasy. 不要复制并粘贴此内容,但是触发keyUp事件的套接字很容易。

var input = document.getElementById("inputfield");
input.addEventListener("keyUp", function() {
    io.emit("aKeyWasPressed", {value:this.value}); //on key up, send input value to Node
}, false); //false for bubbling event

take a look at jQuery $.ajax() method. 看一下jQuery $ .ajax()方法。 http://api.jquery.com/jquery.ajax/ http://api.jquery.com/jquery.ajax/

You can use the jquery-ui autocomplete for your autocomplete functionality. 您可以将jquery-ui自动完成功能用于自动完成功能。 http://jqueryui.com/autocomplete/ http://jqueryui.com/autocomplete/

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

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