dman
dman

Reputation: 11064

Flask Python String Not Returning Back To Javascript XMLHttpRequest call

I have a Javacscript XMLHttpRequest call which calls python app.py(using flask). The python script myapp.py returns "Hello World". I see in Chromium Debug that is is returning "hello world". But it's not being return to the Javascript XMLHttpRequest in the responsetext value.

Here is my javascript code:

function foo() {
    var xml = new XMLHttpRequest();
    xml.open("GET", "/myapp/web.py", true);
    xml.send(null);
    var text = xml.responseText;
    alert(text);

}

Here is the python script:

flask python # cat myapp.py
from flask import Flask
app = Flask(__name__)


@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def catch_all(path):
    return "hello world"

#@app.route('/')
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    app.run()

Upvotes: 0

Views: 1802

Answers (3)

Chanming
Chanming

Reputation: 1

I believe that you have been solve this problem. A way to solve this problem is that you should check the xml.readyState==4 && xml.status == 200

Upvotes: 0

yakiang
yakiang

Reputation: 1634

try :

function foo() {
    var xml = new XMLHttpRequest();
    xml.onreadystatechange() {
        var text = xml.responseText;
        alert(text);
    }
    xml.open("GET", "/myapp/web.py", true);
    xml.send(null);
}

Upvotes: 0

zs2020
zs2020

Reputation: 54522

You need to use a callback function to get the data due to the asynchronous nature of JavaScript.

function ajaxSuccess () {
    alert(this.responseText);
}

function foo() {
    var xml = new XMLHttpRequest();
    xml.open("GET", "/myapp/web.py", true);
    xml.send(null);
    xml.onload = ajaxSuccess;
}

Upvotes: 1

Related Questions