我尝试使用Ajax向我的python(Google App Engine)服务器发送POST请求,就像我们从表单提交一样,但它无法正常工作。
这是我的HTML:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<button>apple</button>
<form method="POST" action="/">
<input name="url" value="value1" id="urlimg">
<br>
<input class="myButton" type="submit" value="FIND OUT" id="submit_button">
</form>
<script type="text/javascript">
$(document).ready(function(){
$('button').click(function() {
$.post('/', { url: 'value1'});
});
});
</script>
</body>
</html>
这是我的python代码:
import os
import webapp2
import jinja2
import urllib2 as urllib
template_dir = os.path.join(os.path.dirname(__file__), '')
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir),
autoescape = True)
class Handler(webapp2.RequestHandler):
def write(self,*a,**kw):
self.response.write(*a,**kw)
def render_str(self,template,**params):
t = jinja_env.get_template(template)
return t.render(params)
def render(self,template,**kw):
self.write(self.render_str(template,**kw))
class MainHandler(Handler):
def get(self):
self.render('image.html')
def post(self):
url = self.request.get('url')
self.response.write(url + ' is your url')
app = webapp2.WSGIApplication([
('/', MainHandler)
], debug=True)
答案 0 :(得分:0)
您应该将响应作为JSON对象返回:
[u'@hummus grill- FINALLY HERE!! With Sonya and co']
然后在模板中处理响应:
class MainHandler(Handler):
def get(self):
self.render('image.html')
def post(self):
import json
url = self.request.get('url')
response_dict = {
'message': 'Yay, I did it!',
'url': url + ' is your url',
}
self.response.headers['Content-Type'] = 'application/json'
self.response.out.write(json.dumps(response_dict))