【问题标题】:How to write to localStorage and post textarea with one click?如何一键写入localStorage并发布textarea?
【发布时间】:2011-11-13 09:13:09
【问题描述】:

我有一个处理程序 /choice 和一个 textarea 字段,/choicehandler 将返回的信息写入数据库。但在发布表单之前,我想写一个用户名到localStorage

这是表格:

<form name="choice_form" action="/choicehandler" method="post">
  <textarea name="choice" rows="7" cols="50"></textarea><br />
  <input type="submit" value="submit your choice">
</form>

点击时我想为用户分配一个用户名并将其写入localStoragewriteToStorage()

<head>
<script type="text/javascript">

var count = 0;

function writeToStorage()
{ 
    user = "user" + count;
    count++;
    localStorage.setItem("chooser", user);
};

</script>
</head>

我很困惑的是如何使用onclick="writeToStorage()"来调用writeToStorage(),同时在表单中有action="/choicehandler"

实现这样的事情的正确方法是什么。我正在使用 Google App Engine (Python),我将在稍后解决此问题后将 ajax 调用添加到 /choicehandler

作为总结,我想一键将javascript变量user写入localStoragepost textarea到/choicehandler

更新

我正在尝试john_doe's answer,但writeToStorage() 从未被解雇。我究竟做错了什么?处理程序的完整代码如下:

class Choice(webapp.RequestHandler):
    def get(self):
        self.response.out.write("""
<html>
  <head>
<script type="text/javascript">

var count = 0;

function writeToStorage()
{ 
    alert("count: " + count);
    user = "user" + count;
    //this line was giving an error; now it is fixed
    //alert("user: " + user and "count: " + count);
    alert("user: " + user + " and count: " + count);
    count++;
    localStorage.setItem("chooser", user);

};
</script>

  </head>
  <body>


<form name="choice_form" id="choice_form" action="/choicehandler" method="post" onsubmit="writeToStorage()">
  <textarea name="choice" rows="7" cols="50"></textarea><br />
  <input type="submit" value="submit your choice">
</form>""")

        self.response.out.write("""
  </body>
</html>""")

【问题讨论】:

  • 你目前的技术有什么问题?
  • 我不清楚在哪里或如何使用onclick="writeToStorage()"

标签: javascript python html


【解决方案1】:

让您的函数在表单提交之前立即被调用。

<form name="choice_form" action="/choicehandler" method="post" onsubmit="writeToStorage()">
  <textarea name="choice" rows="7" cols="50"></textarea><br />
  <input type="submit" value="submit your choice">
</form>

【讨论】:

  • 我一直在尝试这个,但writeToStorage() 永远不会触发。我究竟做错了什么?我用我正在尝试的代码更新了问题。
  • 我发现了错误,其中一个警报中有一个错误的引用,现在一切正常。谢谢。
  • 您能更详细地解释一下提交表单时会发生什么吗?当我尝试获取 POST 和 XHR 时,我无法同时获取它们,似乎表单被发送了两次。这是问题:stackoverflow.com/questions/8114926/…
【解决方案2】:

你可以稍微改变你的功能(有很多方法可以做到这一点)。在表单中添加一个 ID (id="choice_form"),然后添加一行来提交表单:

function writeToStorage() {      
    user = "user" + count;     
    count++;    
    localStorage.setItem("chooser", user); 
    document.getElementById("choice_form").submit();
}

【讨论】:

  • 我试过这个版本,john_doe 和writeToStorage 没有触发。我试过&lt;button type="button" onclick="writeToStorage()"&gt;write to storage&lt;/button&gt; 也没有帮助。我做错了什么?
  • 其中一个警报中有一个错误的引用,现在它正在工作。谢谢。
猜你喜欢
  • 1970-01-01
  • 2011-12-15
  • 2016-05-31
  • 2023-04-04
  • 1970-01-01
  • 1970-01-01
  • 2020-01-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多