2011-11-12 20 views
0

我有一個處理程序/choice與textarea字段和/choicehandler寫入返回到數據庫的信息。但是在發佈表單之前,我想寫一個用戶名到localStorage如何通過一次點擊寫入localStorage併發布textarea?

這是形式:

<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> 

在點擊我要一個用戶名分配給用戶,並將其與writeToStorage()寫入localStorage

<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變量userlocalStoragepost textarea到/choicehandler只需點擊一下。

UPDATE

我想john_doe's answerwriteToStorage()永遠不會被解僱。我究竟做錯了什麼?處理程序的完整代碼如下:

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>""") 
+0

你目前的技術有什麼問題? – lonesomeday

+0

我不清楚在哪裏或如何使用'onclick =「writeToStorage()」' – Zeynel

回答

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> 
+0

我一直在嘗試這個,但'writeToStorage()'永遠不會觸發。我究竟做錯了什麼?我用我正在嘗試的代碼更新了這個問題。 – Zeynel

+0

我發現錯誤,其中一個警報中有一個錯位的引號,現在它全部正常工作。謝謝。 – Zeynel

+0

你能否解釋一下更多的細節當表單被提交時會發生什麼?當我嘗試獲取POST和XHR時,我無法同時獲得它們,似乎表單發送了兩次。這是問題:http://stackoverflow.com/questions/8114926/can-i-test-xmlhttprequest-in-sdk-with-localhost – Zeynel

1

你可以改變你的功能(有很多方法來做到這一點)。一個ID添加到您的表格(ID =「choice_form」),然後添加提交表單行:

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

我試過這個版本,john_doe's和'writeToStorage'沒有開火。我嘗試過'',那也沒有幫助。我究竟做錯了什麼? – Zeynel

+0

其中一個警報中存在錯誤的報價,現在它正在工作。謝謝。 – Zeynel