首页 > 解决方案 > 如何检测使用 webapp2 单击了哪个图像按钮(输入类型 = 图像)?

问题描述

如何确定在 Google App Engine (GAE) 下运行的 Python 脚本中,input type=image点击了网页上的哪个 (imagebutton)(使用 webapp2 处理程序)?

我有一个带有两个(目前将有更多)图像按钮的网络表单,我需要知道点击了哪个按钮。我看过一个关于使用按钮的 id 属性的答案。但它没有使用 Python / webapp2,所以我不确定如何应用它,而且我可能无法正确理解它。

我尝试了很多东西都不起作用,这是我的起点

imgid = handler.request.id

在 POST 处理程序中,但这给出了属性错误。

搜索有关图像按钮和webapp2请求的各种信息资源,除了单击指针的图像中的坐标之外,我几乎看不到从图像按钮将信息返回到服务器。我确实了解到,与其他按钮不同,图像按钮不使用 value 属性;并且在不同的环境(ASP.NET,而不是 Python/webapp2 )中有一篇文章说要使用 id 属性,但这在 Python 中不起作用。

(使用 value 属性,与其他输入按钮类型不使用相同的方法似乎很奇怪。)

这是 POST 处理程序尝试获取 id 的代码:

class image_button_set(webapp2.RequestHandler):
    def sails_spin_set(handler, SLurl):
        imgid = handler.request.id

    

这是表单的 HTML 内容

<form action="/image_button_set" method="post">
    <input name="parm1" id="Button1" type="image" src="/images/spin-glasses3.jpg" height="256" width="256">
    <input name="parm1" id="Button2" type="image" src="/images/spin-spiral3.jpg" height="256" width="256">
    <input name = "parm1" value="Cancel" style="font-size: 16pt; color: DarkRed; font-weight: bold;" type="submit">
</form>

以下是代码如何查找其他类型的按钮,例如收音机(省略无关的日志记录代码等):

class image_button_set(webapp2.RequestHandler):
    def sails_spin_set(handler, SLurl):
       image = self.request.get("image")

HTML中的按钮定义是

<input name="image" value="image1" type="radio">Image1
<input name="image" value="image2" type="radio">Image2

标签: pythonimagebuttonwebapp2

解决方案


我通过formaction使用imagebutton.

<form action="/sails_spin_set?img=dummy" method="post">
  <input type="image" name="spin" formaction="/imgbtn_set?img=spin1" src="/images/spin-glasses3.jpg" style="font-size: 12pt; color: Navy; font-weight: bold;" height="256" width="256">
  <input type="image" name="spin" formaction="/imgbtn_set?img=spin2" src="/images/spin-spiral3.jpg" style="font-size: 12pt; color: Navy; font-weight: bold;" height="256" width="256"><br>
  <br>
  <input name="act" value="Cancel" style="font-size: 16pt; color: DarkRed; font-weight: bold;" type="submit">
</form>

然后以通常的方式处理 URL,在主脚本中路由:

app = webapp2.WSGIApplication(
                              [('/', MainPage),
                               ('/imgbtn_show', image_button_show),
                               ('/imgbtn_set', image_button_set)])
                                  

以及为此的 POST 处理程序:

class image_button_set(webapp2.RequestHandler):
    def post(self):
        imageid = self.request.get("img")  # from the selected imagebutton
        handler.response.write("image selected: "+imageid)

推荐阅读