【问题标题】:JSON passed from Python (Flask) into JavaScript is displaying on screen从 Python (Flask) 传递到 JavaScript 的 JSON 显示在屏幕上
【发布时间】: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


【解决方案1】:

原来我上面的代码有很多问题,其中一些我不得不在相关问题here和here中调试。

其中有:

  • 在我原来的 Flask index() 函数中,它会将 JSON 数据转储到屏幕上,因为我没有在任何地方渲染 index.html 模板。
  • 我在 Flask 函数中有匹配的路由 ('/') 和函数名称 (index())
  • 如 cmets 中所述,我使用 dataType: json 和 array_data = JSON.parse(JSON_array) 对 JSON 进行了不必要的双重解析
  • 此异步函数的返回总是未定义,因为它在调用解决之前被引用
  • 在我以后对 Deferred 对象的更新中,success 属性应该是:success: function(data) { deferredData.resolve(data);}

所以,在所有这些修复之后,这里是功能代码!

Flask/Python:

from flask import Response, json, render_template, jsonify
from app import app
from motifs import get_motif, get_motif_list

@app.route('/ajax')
def ajax() :
    motifs = get_motif_list(10)
    return Response(json.dumps(motifs), mimetype='application/json')

@app.route("/")
def index():
     return render_template("index.html")

JavaScript:(注意:这是我上面问题中的foo() 函数)

function getData() {

    var deferredData = new jQuery.Deferred();

    $.ajax({
        type: "GET",
        url: "/ajax",
        dataType: "json",
        success: function(data) { 
            deferredData.resolve(data);
            },
        complete: function(xhr, textStatus) {
            console.log("AJAX Request complete -> ", xhr, " -> ", textStatus);
            }
    });

    return deferredData; // contains the passed data
};


// I used the Deferred structure below because I later added Deferred objects from other asynchronous functions to the `.when`

var dataDeferred = getData();

$.when( dataDeferred  ).done( function( data ) {
    console.log("The data is: " + data);    
});

【讨论】:

  • 我也面临同样的问题。但是,就我而言,我使用的是纯 JavaScript。所以你能帮我如何在纯 JavaScript 中使用Deferred。提前致谢。
【解决方案2】:

在你的 javascript 中:

function foo() {
var array_data;

$.ajax({
    type: "GET",
    url: "/",
    dataType: "json"
});

request.done(function(JSON_array) {

    /*JSON_array is already parsed and it is an object..*/

    array_data = JSON.parse(JSON_array)["array"]
    /* ^ I belive you dont have to do this ^*/

    console.log(array_data);
    /* ^ change this to console.log(JSON_array);*/
});

return array_data;
/* ^ change this to return JSON_array;*/
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-24
    • 2021-10-27
    • 2016-05-05
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多