Java脚本:使用AJAX调用Flask API失败

时间:2018-01-26 01:20:38

标签: python ajax flask

我在JS中尝试使用简单的Flask API,但它失败了。我使用curl测试了URL,它运行正常。不确定我做错了什么。非常感谢您的帮助。

http响应代码很好(200)。我编写js的方式可能有些不对劲......

python脚本:

from flask import Flask
import simplejson as json

app = Flask(__name__)

@app.route('/api/person', methods=['GET'])
def get_person():
    str = {'id':'1','first_name':'John','last_name':'Smith'}
    res = json.dumps(str)
    return res

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

testapp.js:

$(document).ready(function() {
    $.ajax({
        type: "GET",
        url: "http://localhost:5000/api/person",
        success: function(data){
           $('.person-id').append(data.id);
           $('.person-first_name').append(data.first_name);
           $('.person-status').append('success');
        },
        error: function(){
           $('.person-status').append('failed');
        }

    });
});

的index.html:

<!DOCTYPE html>
<html>
    <head>
        <title>TestApp jQuery</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script src="testapp.js"></script>
    </head>

    <body>
        <div>
            <p class="person-status">The Status is </p>
            <p class="person-id">The ID is </p>
            <p class="person-first_name">First name is </p>
        </div>
    </body>
</html>

html response

curl testing

1 个答案:

答案 0 :(得分:0)

好像你的api返回一个stringify json,

尝试:

$(document).ready(function() {
    $.ajax({
    type: "GET",
    url: "http://localhost:5000/api/person",
    success: function(data){
       data=JSON.parse(data)
       $('.person-id').append(data.id);
       $('.person-first_name').append(data.first_name);
       $('.person-status').append('success');
    },
    error: function(){
       $('.person-status').append('failed');
    }
    });
});

$(document).ready(function() {
$.ajax({
    type: "GET",
    dataType:"json",
    url: "http://localhost:5000/api/person",
    success: function(data){
       $('.person-id').append(data.id);
       $('.person-first_name').append(data.first_name);
       $('.person-status').append('success');
    },
    error: function(){
       $('.person-status').append('failed');
    }
});
});