【发布时间】:2011-12-28 19:16:47
【问题描述】:
我正在尝试以 user1、user2、user3 等形式向每个新用户颁发用户名。
作为my previous question 的结果,现在我知道我需要在应用程序中而不是在浏览器中跟踪计数。所以我创建了/counthandler(我正在使用 Google App Engine Python):
class CountHandler(webapp.RequestHandler):
def get(self):
count = count + 1
在/choice,我有这个脚本:
function writeToStorage()
{
var user = "user" + count;
localStorage.setItem("chooser", user);
document.getElementById("form_chooser").value = user;
};
如何从/counthandler 获取“计数”到writeToStorage?我知道我需要使用 HMLHttpRequest,但不确定如何使用。谢谢。
更新
针对 jfriend00 的评论,我添加了更多关于 ajax 调用的具体问题:
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:8086/counthandler", true);
xhr.onreadystatechange = function (aEvt) {
if (xhr.readyState == 4 && xhr.status == 200){
console.log("request 200-OK");
}
else {
console.log("connection error");
}
};
//I am not sure what to put in send()?
xhr.send();
更新 2
响应 jfriend00 的评论和提供的参考,我将调用更改为 GET;但不确定之后会发生什么:
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:8086/counthandler", true);
xhr.onreadystatechange = function (aEvt) {
if (xhr.readyState == 4 && xhr.status == 200){
console.log("request 200-OK");
}
else {
console.log("connection error");
}
};
//changed this to "null". this now opens the connection.
//what do I do after this?
xhr.send(null);
更新回答 jfriend00 的更新回答:
感谢您的详细解释。现在我明白了。但是我仍然缺少一些东西。很容易得到count的值:
query = Count.all()
query.get()
count = e.count
logging.info("count = %s" % count)
# gives count = 12
现在你说的是,将python变量“count”的值为12赋给js变量“count”
<script type="text/javascript">
var count = 12;
</script>
我不明白的是下次count = 13时会发生什么?
在我看来
<script type="text/javascript">
var count = count;
</script>
不会工作。正确的?我错过了什么?
再次感谢。
更新以尝试 jfriend00 答案中的第二个选项。看来我需要包含一个成功函数来获取/counthandler发送的“count”变量:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (xhr.readyState == 4 && xhr.status == 200)
{
//get "count" sent by /counthandler?
//var count = count;
}
};
xhr.open("POST", "http://localhost:8086/counthandler", true);
xhr.send(null);
但我仍然不明白/counthandler 如何发送“计数”以及如何在成功函数中获取它。
【问题讨论】:
-
你为什么要使用localStorage?你原来的理由,即存储一个全局计数器,不再相关,那么为什么还要使用它呢?
-
@DanielRoseman;我想写下我给用户的用户名,例如“user1”,这样我就可以跟踪 user1 制作的 cmets。这有意义吗?
标签: javascript python xmlhttprequest