Laravel + socket.io에 프로젝트가 있습니다. 방송중인 json의 특정 필드에 액세스해야합니다. 다음은 코드입니다.
socket.js
redis.on('message', function(channel, message) {
message = JSON.parse(message);
io.emit(channel + ':' + message.event,message.data);
});
내 클라이언트 소켓에는 이것이 있습니다.
socket.on("comment-channel:App\\Events\\CommentEvent", function(message){
alert(message.data);
});
그러면 성공적으로 경고합니다.
[{
"id": 136,
"content": "dffsadf",
"user_id": "1",
"task_id": "33",
"created_at": "2016-03-29 10:47:19",
"user": {
"id": 1,
"first_name": "Hulk",
"last_name": "Hogan",
"username": "",
"email": " [email protected]",
"company_id": "1",
"role_id": "0",
"photo": "\/assets\/apps\/img\/photos\/lvrv5VOGRskwPHvFVakp.jpeg",
"position": "asdfsadf",
"phone": "+75843857834",
"city": "",
"country": "Singapore",
"timezone": "",
"created_at": "2016-03-10 04:16:24",
"updated_at": "2016-03-10 07:54:12",
"deleted_at": null
}
}]
그럼 이거 먹으면
alert(message.data.task_id);
또는
alert(message.data['task_id']);
나는 '정의되지 않음'을 얻는다 ..
task_id에 어떻게 액세스 할 수 있습니까? 감사합니다 !!!!
message.data
배열 인 것 같습니다. alert(message.data[0].task_id);
편집 : 작동하지 않으면 문제가 없습니다 ...
var message = {
data : [{
"id" : 136,
"content" : "dffsadf",
"user_id" : "1",
"task_id" : "33",
"created_at" : "2016-03-29 10:47:19",
"user" : {
"id" : 1,
"first_name" : "Hulk",
"last_name" : "Hogan",
"username" : "",
"email" : " [email protected]",
"company_id" : "1",
"role_id" : "0",
"photo" : "\/assets\/apps\/img\/photos\/lvrv5VOGRskwPHvFVakp.jpeg",
"position" : "asdfsadf",
"phone" : "+75843857834",
"city" : "",
"country" : "Singapore",
"timezone" : "",
"created_at" : "2016-03-10 04:16:24",
"updated_at" : "2016-03-10 07:54:12",
"deleted_at" : null
}
}
]
};
alert(message.data[0].task_id);
편집 2 당신 message.data
이 문자열로 구문 분석되지 않았습니까? json 객체로 캐스팅하려고
var message = {
data : '[{\r\n' +
' "id" : 136,\r\n' +
' "content" : "dffsadf",\r\n' +
' "user_id" : "1",\r\n' +
' "task_id" : "33",\r\n' +
' "created_at" : "2016-03-29 10:47:19",\r\n' +
' "user" : {\r\n' +
' "id" : 1,\r\n' +
' "first_name" : "Hulk",\r\n' +
' "last_name" : "Hogan",\r\n' +
' "username" : "",\r\n' +
' "email" : " [email protected]",\r\n' +
' "company_id" : "1",\r\n' +
' "role_id" : "0",\r\n' +
' "photo" : "\/assets\/apps\/img\/photos\/lvrv5VOGRskwPHvFVakp.jpeg",\r\n' +
' "position" : "asdfsadf",\r\n' +
' "phone" : "+75843857834",\r\n' +
' "city" : "",\r\n' +
' "country" : "Singapore",\r\n' +
' "timezone" : "",\r\n' +
' "created_at" : "2016-03-10 04:16:24",\r\n' +
' "updated_at" : "2016-03-10 07:54:12",\r\n' +
' "deleted_at" : null\r\n' +
' }\r\n' +
' }\r\n' +
' ]'
};
var obj = JSON.parse(message.data);
alert(obj[0].task_id);
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다