Tornado doesn't send Ajax response to client

2019-07-20 02:19发布

Upon form submit the Tornado server does some checks and sends a response back to the client, which should appear in that current page as an alert.

Instead a blank html page is rendered with the Json response, but not as an alert on the current page where the form was submitted.

On submit the form is sent via post to /dh (DataHandler)

This is the Jquery:

$.post("/dh",function(data,status){
    alert("Data: " + data + "\nStatus: " + status);
    },"json");

The Tornado code:

class DataHandler(BaseHandler): 
    def post(self):

        # Checks are done with form data received

        dupInfo={
            'tel' : duptel,
            'name' : dupName
             }

        self.write(json.dumps(dupInfo, default=json_util.default))
        self.finish()

So how can you return this json to the current page?

2条回答
虎瘦雄心在
2楼-- · 2019-07-20 02:50

Give your form an id and stop the default redirect after submission:

$("#yourForm").submit(function (event) {
    event.preventDefault();

    jQuery.ajax({
        url: "/dh",
        data: {
        // whatever data you are passing to handler
        },
        dataType: "json",
        type: "POST"
    }).done(function (data, textStatus, jqXHR) {
       // call was successful
       // access response data
       alert(data['tel'])
       alert(data['name'])
    }).fail(function (jqXHR, textStatus, errorThrown) {
       // call error
       // access response data
       var data = jqXHR.responseJSON;
       alert(data['tel'])
       alert(data['name'])
    });
});

Based on your handler, you should end up in the done callback rather than the fail one.

查看更多
淡お忘
3楼-- · 2019-07-20 02:55

After the "alert" statement, add return false;. This disables the browser's default handling of the POST event. The browser's default behavior is to navigate to the new URL, and you want to prevent that.

查看更多
登录 后发表回答