我正在嘗試將Channel API與我的Google App Engine django-nonrel項目一起使用。根據我當前的要求,我想將位於某個頁面的所有用戶列表(例如group_mainpage.html
)發送給位於同一頁面上的所有其他用戶。換句話說,如果我們都在這個頁面上,我們都可以在這個頁面的角落裏看到我們的名字。一旦用戶從頁面移出,他們的名字應該從列表中刪除。但是我無法正確製作JSON並顯示它。直到現在我也做過這樣的,但它不工作:simplejson在Google App Engine頻道API中轉儲
group_mainpage.html
<html>
<head>
</head>
<body>
<div id="channel_api_params" style="display:none;" chat_token="{{chat_token}}" channel_id="{{channel_id}}"></div>
<div align="center"><font size="5" color="blue">Welcome To Group Main Page</font><br><br>
</div>
<div align="center">
<form method="POST" action="/group_start/">
<input type='submit' value="Start">
</form>
<div id="mydiv">
{% include 'user_list.html' %}
</div>
</div>
<script type="text/javascript" src="/media/jquery.js"></script>
<script type="text/javascript" src="/_ah/channel/jsapi"></script>
<script type="text/javascript">
$(document).ready(function(){
$(window).load(function(){
var channel_id = $('#channel_api_params').attr('channel_id');
$.ajax({
url: '/valid_group_users/',
type: 'GET',
data:{
'channel_id':channel_id,
},
success: function(current_user){
},
complete: function(){
}
});
var chat_token = $('#channel_api_params').attr('chat_token');
var channel = new goog.appengine.Channel(chat_token);
var socket = channel.open();
socket.onopen = function(){
};
socket.onmessage = function(m){
var data = $.parseJSON(m.data);
$('#mydiv').append(data['post_element']);
};
socket.onerror = function(err){
alert("Error => "+err.description);
};
socket.onclose = function(){
alert("channel closed");
};
});
});
</script>
</body>
</html>
views.py
def valid_group_users(request):
channel_id=request.GET['channel_id']
group_initialise=Group_initialise()
group_initialise.channel_id=channel_id
group_initialise.user_name=request.user
group_initialise.save()
try:
data=Group_initialise.objects.all()
except:
pass
#As per the suggestions of Kevin:
user_list=[]
for result in data:
user_list.append(result.user_name)
template_values={'user_list':user_list}
temp_result={'post_element':render_to_response("user_list.html",template_values)}
channel_msg=simplejson.dumps(temp_result)
for result in data:
if result.user_name!=request.user:
channel.send_message(result.channel_id,channel_msg)
user_list.html
{% for users in user_list %}
<div class="message">
<span>
{{users}}:
</span>
</div>
{% endfor %}
編輯:
temp_result=str(temp_result)
#To remove Http-Header/content-type copy string after 40 characters
temp_result=temp_result[40:]
#Replace colon attaching automatically at the end of every user_name
temp_result=temp_result.replace(':','')
channel_msg=simplejson.dumps(temp_result)
你說這不起作用,但是*發生了什麼?你有錯誤嗎?數據看起來不正確?更多細節會有所幫助。 – Herms
Hello Herms,我得到的錯誤是'不是JSON可序列化' –
SRC