龙卷风中的Ajax响应有关self.write使用的一些问题

时间:2015-02-02 10:30:23

标签: jquery ajax tornado

我仍然不熟悉龙卷风,如果有关于这个问题的明显答案我很抱歉^ _ ^。

我想使用self.write从龙卷风到js得到响应。当我使用self.write时,当然响应被传递给js但网站将转到一个新页面回复的消息。我不希望这种情况发生,但我不知道如何处理它。 例如

class IndexHandler(tornado.web.RequestHandler):
''' handler the "/" action '''
def get(self):
    self.render("index.html")

def post(self):
    name = self.get_argument("name", "None")
    n = "123"
    print name
    if name != n :
        self.write("F")
        print "index1"
    else:
        self.write("T")
        print "index2"

并且有js

$("p").css("display", "none");

$(document).ready(function() {
$("#myButton").click(function(event){
    event.preventDefault();
    $.post("/", {name: $("#name").val()}, function(data) {

            if (data === "F") {
                $("p").css("display", "block");
                alert(data);
            } else {
                $.get("/person");
                alert(data);
            }
    });
});
});

当数据===“F”时,它会起作用。但是页面立即转向只有数据的页面。我不希望发生这种情况。我该怎样处理它?<​​/ p>

我很遗憾忘记发布HTML代码。 这是html中的代码:

<!DOCTYPE html>

             

</head>

<body>
    <form method="post" id="myForm">
        <input type="text" id="name" name="name">
        <input type="submit" id="myButton" name="button">
    </form>
    <p>inform!</p>

    <script type="text/javascript" src={{ static_url("index.js") }}>      </script>
</body>

1 个答案:

答案 0 :(得分:0)

您可以使用preventDefault()调用来阻止页面重定向:

$("#myButton").click(function(e){
    e.preventDefault();
    $.post("/", {name: $("#name").val()}, function(data) {
        if (data === "F") {
            $("p").css("display", "block");
            alert(data);
        } else {
            $.get("/person");
            alert(data);
        }
    });
});