【发布时间】:2014-05-28 18:58:17
【问题描述】:
我将来自 Python 后端的 JSON 传递到我正在运行 webGL (three.js) 动画的前端 JavaScript。 JSON 包含确定动画中发生的情况的数值。我的问题是,虽然我有一个基本的 ajax 请求工作,但 JSON 被打印到屏幕上(代替动画)而不是成为一个变量,我可以通过迭代来控制动画的各个方面。调用的两半如下所示。
我之前向这个人问过related question 并得到了一些很大的帮助,但显然我仍然缺少一块拼图。我一直在阅读文档和各种资源,但需要朝着正确的方向轻推才能最终使其正常工作。任何帮助表示赞赏!
在python后端:
from flask import Response, json, render_template, jsonify
from app import app
from motifs import get_motif, get_motif_list
@app.route('/')
def index():
motifs = get_motif_list(10)
# The first version of the return below successfully sends data, yet it is printed to the
# screen, rather than being stored as data in a variable.
return Response(json.dumps(motifs), mimetype='application/json')
# This version of the return does not work:
# return render_template("index.html", motifs = motifs)
在 JavaScript 中(请注意,console.log 健全性检查不起作用 - 我不知道为什么:
function foo() {
var array_data;
$.ajax({
type: "GET",
url: "/",
dataType: "json"
});
request.done(function(JSON_array) {
array_data = JSON.parse(JSON_array)["array"]
console.log(array_data); // sanity check - doesn't work
});
return array_data;
};
var array = foo();
console.log(array); // sanity check - doesn't work
更新
在以下建议的帮助下,我已经很接近实现这一目标了。 JSON 不再打印到屏幕上(由 Flask 返回引起的问题),我已经解决了一路上发现的 multifunction callback issue。但是,我现在从complete textStatus 得到一个parsererror。我认为现在的问题在于 Python/Flask(参见下面的当前代码)。再次感谢所有帮助过的人!
Python/Flask(我认为问题出在这里 - 我是 Flask 的菜鸟):
from flask import Response, json, render_template, jsonify
from app import app
from motifs import get_motif, get_motif_list
@app.route('/')
def index():
motifs = get_motif_list(10)
return Response(json.dumps(motifs), mimetype='application/json')
@app.route("/")
def index():
return render_template("index.html")
JavaScript(数据由 Deferred 对象返回 - 用于解决回调问题):
function getData() {
var deferredData = new jQuery.Deferred();
$.ajax({
type: "GET",
url: "/",
dataType: "json",
success: deferredData.resolve(),
complete : function(xhr, textStatus) {
console.log("AJAX REquest complete -> ", xhr, " -> ", textStatus)}
});
return deferredData; // contains the passed data
};
【问题讨论】:
-
dataType: "json"可能已经将您的数据强制转换为 json。首先在 request.done 函数中进行调试。 -
dataType: "json"已经为您解码响应。 -
将以下回调添加到您的 ajax 调用中,并查看控制台中记录的 textStatus 内容。完成:函数(xhr,textStatus){console.log(“AJAX请求完成->”,xhr,“->”,textStatus)}
-
@gromiczek 要求是否包括在
foo()完成后调用JSON_array,在scope的foo之外?要求是否包括定义为全局变量的JSON_array?谢谢 -
@guest271314 - 感谢您的提问。最后我需要将 JSON_array 传递给代码中的另一个模块,所以是的,我需要在
foo的范围之外调用它,但最终它不会是全局的。我需要一段时间来解决这个问题,因为我也意识到需要学习如何在我的脚本中处理多个回调。我有另一个异步(非 ajax/jquery)请求,我需要处理这个对数据库的调用。
标签: javascript jquery python json flask