通过 Websocket 控制器打印从 Stomp 传入的 json 数组
Print json array incoming from Stomp over Websocket controller
我添加到我的类路径 jackson 数据绑定..
这是我的 java 代码(服务器端)
@MessageMapping("/hello")
@SendTo("/topic/whoIsOnline")
public List<User> greeting(String name) throws Exception {
List<User> list = new ArrayList<User>();
User user = new User();
user.setEmail("test@gmail.com");
list.add(user);
User user1 = new User();
user1.setEmail("example@gmail.com");
list.add(user1);
System.out.println(list);
return list;
}
这是JS代码..
var stompClient = null;
$(document).ready(function() {
var socket = new SockJS('onlineUsers');
stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/whoIsOnline', function(result) {
var results = result.body;
for(var i in results){
console.log(results[i].email);
}
});
});
});
function sendName() {
var txtUser = $('#txtUser').val();
stompClient.send("/app/hello", {}, JSON.stringify(txtUser));
}
当我写 document.writeln(results) 时,它是这样打印的...
[{"email":"test@gmail.com"},{"email":"example@gmail.com"}]
但是,我想这样打印..
test@gmail.com
example@gmail.com
for 循环不工作..
for(var i in results)
{
console.log(results[i].email);
}
试试下面的代码
var results = result.body;
var data = JSON.parse(results);
for(var i in data){
console.log(data[i].email);
}
我添加到我的类路径 jackson 数据绑定..
这是我的 java 代码(服务器端)
@MessageMapping("/hello")
@SendTo("/topic/whoIsOnline")
public List<User> greeting(String name) throws Exception {
List<User> list = new ArrayList<User>();
User user = new User();
user.setEmail("test@gmail.com");
list.add(user);
User user1 = new User();
user1.setEmail("example@gmail.com");
list.add(user1);
System.out.println(list);
return list;
}
这是JS代码..
var stompClient = null;
$(document).ready(function() {
var socket = new SockJS('onlineUsers');
stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/whoIsOnline', function(result) {
var results = result.body;
for(var i in results){
console.log(results[i].email);
}
});
});
});
function sendName() {
var txtUser = $('#txtUser').val();
stompClient.send("/app/hello", {}, JSON.stringify(txtUser));
}
当我写 document.writeln(results) 时,它是这样打印的...
[{"email":"test@gmail.com"},{"email":"example@gmail.com"}]
但是,我想这样打印..
test@gmail.com
example@gmail.com
for 循环不工作..
for(var i in results)
{
console.log(results[i].email);
}
试试下面的代码
var results = result.body;
var data = JSON.parse(results);
for(var i in data){
console.log(data[i].email);
}