栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在Google App Engine(Python)中使用AJAX

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在Google App Engine(Python)中使用AJAX

好吧,先生,我们走了…一个带有一个故事和无限投票的简单应用… ;-)

app.yaml

application: anotherappnameversion: 1runtime: python27api_version: 1threadsafe: truedefault_expiration: "0d 0h 5m"libraries:- name: jinja2  version: latest- name: webapp2  version: latesthandlers:- url: .*  script: main.app

main.py

import loggingfrom controllers import serverfrom config import configimport webapp2app = webapp2.WSGIApplication([        # Essential handlers        ('/', server.RootPage),        ('/vote/', server.VoteHandler)    ],debug=True, config=config.config)# Extra Hanlder like 404 500 etcdef handle_404(request, response, exception):    logging.exception(exception)    response.write('Oops! Naughty Mr. Jiggles (This is a 404)')    response.set_status(404)app.error_handlers[404] = handle_404

models/story.py

from google.appengine.ext import ndbclass Story(ndb.Model):    title = ndb.StringProperty(required=True)    vote_count = ndb.IntegerProperty(default = 0)

controllers/server.py

import osimport reimport loggingimport configimport jsonimport webapp2import jinja2from google.appengine.ext import ndbfrom models.story import Storyclass RootPage(webapp2.RequestHandler):    def get(self):        story = Story.get_or_insert('Some id or so', title='A voting story again...')        jinja_environment = self.jinja_environment        template = jinja_environment.get_template("/index.html")        self.response.out.write(template.render({'story': story}))    @property    def jinja_environment(self):        jinja_environment = jinja2.Environment( loader=jinja2.FileSystemLoader(     os.path.join(os.path.dirname(__file__),       '../views'     ))        )        return jinja_environmentclass VoteHandler(webapp2.RequestHandler):    def post(self):        logging.info(self.request.body)        data = json.loads(self.request.body)        story = ndb.Key(Story, data['storyKey']).get()        story.vote_count += 1        story.put()        self.response.out.write(json.dumps(({'story': story.to_dict()})))

最后

views/index.html

<!DOCTYPE html><html>    <head>        <base href="/">        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>    </head>    <body>        <h2>{{story.title}}</h2>        <div> <span >{{story.vote_count}}</span>  | <a href="javascript:VoteUp('{{story.key.id()}}');" >Vote Up Story</a>        </div>        <script> function VoteUp(storyKey){     $.ajax({       type: "POST",       url: "/vote/",       dataType: 'json',       data: JSON.stringify({ "storyKey": storyKey})     })     .done(function( data ) { // check why I use done         alert( "Vote Cast!!! Count is : " + data['story']['vote_count'] );         $('.voteCount').text(data['story']['vote_count']);     }); };        </script>    </body></html>

组装,阅读它就足够简单并运行。如果您需要一个可行的git示例,请发表评论。

githublink(从评论)



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/379928.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号