我在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>
答案 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');
}
});
});