我以JSON格式从Python发送数据。我能够获取数据,并在本地托管的页面http://127.0.0.1:5000/上使用检查器中的for循环。但是,当我将相同的JavaScript应用到本地JS文件并将其连接到我的HTML页面时,我总是会从responseJSON中得到未定义的JSON数据。我正在尝试从JSON数据,特别是[10, 20, 30, 40, 50]中获取数组。然后,我可以在for循环中使用它来生成列表。
app3/static/js/index.js
console.log("connected to index.js!!!");
var getData = $.get("/send");
console.log(getData.responseJSON.result);app3/views.py
from flask import Flask, render_template, jsonify
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html")
@app.route("/send")
def send():
return jsonify({"result": [10, 20, 30, 40, 50]})
if __name__ == "__main__":
app.run(debug=True)app3/templates/index.html
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script>
</head>
<body>
<h3>Index</h3>
<script type="text/javascript" src="{{url_for('static',filename='js/index.js')}}"></script>
</body>
</html>Chrome控制台中的错误位于js文件的第5行。具体来说,console.log(getData.responseJSON.result);
Uncaught TypeError: Cannot read property 'result' of undefined
at index.js:5它一开始就起作用了,但现在我一直收到这个错误。在检验员那里工作很好。为什么会发生这种情况?
发布于 2019-03-05 15:39:19
只要看看.get的jquery,就会发现getData似乎没有定义,因为它不返回任何内容。他们的例子是:
$.get( "ajax/test.html", function( data ) {
$( ".result" ).html( data );
alert( "Load was performed." );
});尝试在成功回调中登录。您还可以在devtools中的第5行(使用日志)上设置一个断点,并在一切发生故障之前检查getData。
使用允诺的示例
$.get("/send").then(function (data){
// Executes after response is received
// data is the response returned
console.log(data)
});希望这能有所帮助
https://stackoverflow.com/questions/55006109
复制相似问题