Tornado doesn't send Ajax response to client

◇◆丶佛笑我妖孽 提交于 2019-12-24 00:12:20

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/26738166/tornado-doesnt-send-ajax-response-to-client

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!