2011-11-29 51 views
0

處理器實現使用JavaScript API通道

class TestHandler(RequestHandler, Jinja2Mixin): 
def get(self): 
    channel_id = str(random.randint(1, 10000)) + str(datetime.now()) 
    chat_token = channel.create_channel(channel_id) 
    context = {'channel_id': channel_id, 'chat_token': chat_token} 
    return self.render_response('test.html', **context) 

def post(self): 
    channel_id = str(random.randint(1, 10000)) + str(datetime.now()) 
    chat_token = channel.create_channel(channel_id) 
    context = {'channel_id': channel_id, 'chat_token': chat_token} 
    return self.render_response('test.html', **context) 

HTML實現

<html> 
<head> 
<script type="text/javascript" language="javascript" src="/static/js/jquery-1.6.1.min.js"></script> 
<script type="text/javascript" language="javascript" src="/static/js/backend.js"></script> 
</head> 
<body> 
    <form method="post" id="testform" name="testform"> 
     <br><label name="channel_id" id="channel_id">{{channel_id}}</label> 
     <br><label name="chat_token" id="channel_id">{{chat_token}}</label> 
     <input type="submit" id="btnsubmit" class="btnsubmit" name="btnsubmit" value="submit" /> 
    </form> 
</body> 
</html> 

jQuery的執行

$(document).ready(function() { 

    var token =$('#channel_id').val() 
    alert(token) 

    var channel = new goog.appengine.Channel(token); 
    var socket = channel.open(); 
    socket.onopen = onOpened; 

    onOpened = function() { 
     connected = true; 
     var xhr = new XMLHttpRequest(); 
     xhr.open('POST','/dashboard/', true); 
     xhr.send(); 
    }; 

    socket.onmessage = onMessage; 
    socket.onerror = onError; 
    socket.onclose = onClose; 
}); 

調用後端URL我想打電話給後端處理。我不知道怎麼做。這就是我所做的。任何人都可以提供幫助嗎?

+1

我認爲,Channel API與這個問題大多無關。 –

回答

1

您使用像http://instance.backend.appid.appspot.com這樣的URL訪問後端(請參閱the docs)。由於您無法在http://appid.appspot.com上呈現的頁面中對此頁面生成XHR,因此基本上有兩種選擇:

您可以通過前端的servlet將請求編組到您的後端。所以,你可以這樣做:

class MarshalServlet(RequestHandler): 
    """ This class is part of your frontend. """ 
    def post(self, instance, backend): 
    # generate an urlfetch request to http[s]?://instance.backend.appid.appspot.com 
    # and return its result. 
    # (left as an exercise for the reader) 

# add a "dashboard" handler to your frontend application. 
app = webapp.WSGIApplication([('/dashboard/', MarshalServlet), 
           # other servlets etc. 
          ], debug=True) 

或者你可以使用JSONP做跨域請求,這很容易與jQuery's getJSON method

$.getJSON("http://instance.backend.appid.appspot.com/dashboard/", function() { 
    alert("success"); 
}); 

這不是我清楚你的/儀表板/處理程序會這樣做,所以我不確定它是否可以/應該返回JSON或者您是否關心標題等等。

另請注意,使用getJSON方法不會沿着cookie發送消息,但您可以使用封送處理servlet來完成此操作。