使用javascript渠道API调用后端网址

时间:2011-11-29 05:35:03

标签: jquery python google-app-engine

处理程序实施

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;
 });

我想调用后端处理程序。我不知道怎么做。这就是我所做的。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

您使用http://instance.backend.appid.appspot.com等网址访问后端(请参阅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来执行此操作。