How do I pass form data over a websocket? (socket.io)
<form name="input" action="">
<input type="text" name="say" />
<input type="submit" value="send" />
</form>
I want to send the data in this form to the server via web sockets, i'm using socket.io.开发者_Python百科
What is the best way to achieve this?
You'd need to use .serialize() on the form like so:
var formdata = $('form').serialize();
Then pass that over the websocket. On the node.js side, you can get a JS object back by using querystring.parse:
var querystring = require('querystring');
// Data is the data received from the client
var result = querystring.parse(data);
you can try this
function getFormData2Object(form){
var un_array = form.serializeArray();
var _array = {};
$.map(un_array, function(n, i){
if(n.name.indexOf('[') > -1 ){
var array = n.name.match(/\[(.*?)\]/);
var key = n.name.replace(array[1],"").replace('[',"").replace(']',"");
if(!_array[key]){
_array[key] = {};
}
_array[key][array[1]] = n['value'];
}else{
_array[n['name']] = n['value'];
}
});
return _array;
}
socket.emit('blablabla', getFormData2Object( $("form") ) );
good luck :)
精彩评论