【发布时间】:2017-11-03 01:13:23
【问题描述】:
相关信息:
1) 第一次在这里发帖,慢慢来。
2) 我是菜鸟。
3) 尝试学习 python/Django。
我想做的事:
1) 创建一个英语 -> pig latin 翻译器(用 python 编写)并让它在浏览器中工作。
我希望它如何工作:
1) 用户点击“翻译”按钮,然后使用我现有的 python 函数来翻译他们的输入。
2) 然后翻译会显示在输入下方。
到目前为止我做了什么:
1) 创建 .py 文件,在控制台中成功翻译英语 -> pig latin。
def pigLatin(sentence):
translation = " "
for word in sentence.split():
if word[0] in "aeiou":
translation += word + "yay "
if word[0] and word[1] not in "aeiou":
translation += word[2:] + word[0:2] + "ay"
print("hai")
else:
translation += word[1:] + word[0] + "ay "
return translation
sentence = input("Enter word/sentence you want translated to pig latin below: ")
print(pigLatin(sentence))
2) 使用 Jinja/添加了一些 HTML 和引导程序(请参见下文)
3) 创建了一个 Django 项目,并安装了我的 pig latin 应用程序,我的文件夹结构如下:
--mysite
|
|--pigLatinApp
|----templates
|------pigLatinApp
|--------home.html
|--------header.html
3)尝试使用Ajax让我的按钮工作,我的HTML文件和views.py如下:
header.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Pig Latin Translator</title>
{% load staticfiles %}
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}" type="text/css">
</head>
<body class="body">
<section id="translatorSection">
<!------------------Log Sum Container-------------------------->
<div class="container" id="translatorContainer">
{% block content %}
{% endblock %}
</div>
</section>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js">
</script>
</body>
</html>
home.html
{% extends "pigLatinApp/header.html" %}
{% block content %}
<div class="row">
<div class="col-md-6">
<form>
<h3>Pig Latin Translator</h3>
<p>Enter below what you want translated!</p>
<input type="string" class="form-control" placeholder="Type what you want translated here!" id="inputSumA">
<button id="translateToPig" class="btn btn-success form-control">Translate</button>
<div id="displayTranslation">
<p>{{ output }}</p>
</div>
</form>
</div>
</div>
<script>
$("#translateToPig").click(function() {
$.get("/output/", function(data) {
$("#displayTranslation").html(data);
}, "html");
});
</script>
{% endblock %}
views.py
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return render(request, 'pigLatinApp/home.html')
def output(request):
if request.is_ajax():
py_obj = pigLatinTranslator.test_code(10)
return render(request, 'pigLatinApp/output.html', {'output': py_obj.a})
点击按钮时实际发生的情况:
1) 没什么...页面似乎在刷新。
我们将不胜感激,干杯!
【问题讨论】:
标签: javascript jquery python html django