簡體   English   中英

更新中 <h1> 在GAE上使用Ajax使用python輸出標記代碼

[英]Updating <h1> tag with python output using ajax on GAE

我已經擺弄了一段時間,一直在網上瀏覽。 我是javascript,jquery和AJAX的新手。 如何正確調用此python腳本,以便從函數而不是原始代碼獲取返回輸出?

我正在使用Google App Engine托管一個簡單的名稱生成器類型的應用程序。 因此,我正在本地計算機上(使用本地主機上的應用程序)開發此代碼。 我有一個按鈕,它將返回我的“ generate_name”函數的輸出,並通過jinja2模板引擎將其注入到頁面的html中。 因此,我使用的{{name}}每次按下按鈕時都會被python函數的輸出所代替。

問題是,盡管這在我的機器上正常運行,但一旦在應用程序引擎上啟動,很明顯,每次按下按鈕時,整個頁面都將重新加載以更新新生成的名稱。 效果不好,每次都重新加載頁面上的圖像等。 我決定嘗試使用AJAX來更新包含名稱的'<h1>'標簽。

我將我的名稱生成函數和它使用的單詞列表放入其自己的.py文件中,並編寫了以下腳本:

$(document).ready(function () {
    $('button').click(function () {
        $.ajax({
            type:"GET",
            url:"static/words.py",
            success:function(msg){
                $('h1').html(msg);
            }
        });         
    }); 
});

當我現在按下按鈕時,它只是返回python腳本本身中的實際代碼,而不是像我想要的那樣返回值。 這是python腳本:

#Two large word lists are here

def generate_band_name():
    noun = choice(nouns).strip()
    adj = choice(adjectives).strip()
    return '%s %s' % (adj, noun)

generate_band_name()  

這是該頁面的html:

<html>
    <head>
        <link rel="stylesheet" type="text/css" href="static/main.css">
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script type="text/javascript" src="static/main.js"></script>
        <title>Band name generator</title>
    </head>    
    <body>    
        <div class="main">  
            <img src="static/Graffiti.png"/><br>
            <h1></h1><br>
            <button>GENERATE</button>
        </div>

    </body>
</html>

這是我的app.yaml文件:

application: name-generator
version: 1
runtime: python27
api_version: 1
threadsafe: yes

handlers:
- url: /favicon\.ico
  static_files: favicon.ico
  upload: favicon\.ico


- url: .*/static
  static_dir: static

- url: .*
  script: main.app

libraries:
- name: webapp2
  version: "2.5.2"
- name: jinja2
  version: latest

目錄結構是這樣的:

C:/code/GAE/name-generator/
C:/code/GAE/name-generator/scripts
C:/code/GAE/name-generator/static
C:/code/GAE/name-generator/templates

編輯:

我已將其添加到main.app中:

class Generate(MainHandler):

    def generate_band_name(self):
        noun = choice(nouns).strip()     # choice imported from random
        adj = choice(adjectives).strip() # nouns and adjectives are imported lists
        return '%s %s' % (adj, noun)

    def get(self):
        name = self.generate_band_name()
        # I am unsure how to get the ajax script to access
        # the output of generate_band_name

app = webapp2.WSGIApplication([
    ('/', MainHandler),
    ('/generate', Generate)
], debug=True)

確定先前的答案不正確。 再試一次。 都是關於Yaml的:

- url: .*/static
  static_dir: static

導致這些內容按原樣返回給用戶,例如html,image,javascript等。


類似於您在其他地方的方法:

- url: .*
  script: main.app

您需要將其放入Yaml中以獲取Ajax腳本

- url: /ajax/words.py
  script: /ajax/words.py

編輯 必須有一種映射整個目錄的方法,但是我不知道...

並更新javascript以查看/ajax/words.py 從技術上講,您可以使用主文件夾中的py來執行此操作,但這更加干凈。

您應該將Ajax腳本的服務器端路徑與其他處理程序完全一樣。 也就是說,由於您正在使用webapp2,因此它必須是實際的請求處理程序,接受請求並返回響應,並以與其他處理程序相同的方式映射為腳本URL。 因此,您將不會訪問/foo/bar.py-您將在app.yaml中或(更可能是)在main.py中的路由中映射/ foo / bar,並將其設置為執行該處理程序。

編輯

恐怕我不明白您的榜樣。 但是您似乎確實使事情復雜化了。 這就是我要做的。

<script type="text/javascript">
  $.click('#my_button').function() {
      $.get('/my_ajax_url', function(data) {
          $('#dynamic_content').append(data);
      });
  });

<div id="dynamic_content"></div>
<button id="my_button">click me</button>

main.py:

class MainHandler(RequestHandler):
    def get(self):
        ... load template ...
        self.response.write(my_template.render())

class AjaxHandler(RequestHandler):
    def get(self):
        return json.dumps(generate_band_names())

app = webapp2.WSGI.WSGIApplication([
    ('/', MainHandler),
    ('/my_ajax_url', AjaxHandler)
], debug=True)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM