从Python(Flask)传递到JavaScript的JSON显示在屏幕上 [英] JSON passed from Python (Flask) into JavaScript is displaying on screen

查看:92
本文介绍了从Python(Flask)传递到JavaScript的JSON显示在屏幕上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将JSON从Python后端传递到运行WebGL(three.js)动画的前端JavaScript中. JSON包含确定动画中将发生什么的数值.我的问题是,尽管我有一个基本的ajax请求正在工作,但JSON却被打印到屏幕上(代替了动画),而不是成为一个可以迭代以控制动画各方面的变量.通话的两半如下所示.

I am passing a JSON from a Python back-end into my front-end JavaScript where I'm running a webGL (three.js) animation. The JSON holds numerical values that determine what happens in the animation. My problem is that while I have a basic ajax request working, the JSON is being printed to the screen (in lieu of the animation) rather than becoming a variable I can iterate through to control aspects of the animation. The two halves of the call are shown below.

我之前曾对此问题提出过一个相关问题,并获得了很大的帮助,但显然仍然缺少一个问题难题.我一直在阅读文档和各种资源,但是需要朝着正确的方向微调才能最终使该功能生效.感谢您的帮助!

I asked a related question to this one before and got some great help, but am obviously still missing a piece of the puzzle. I've been reading docs and all sorts of sources, yet need a nudge in the right direction to finally get this working. Any help is appreciated!

在python后端中:

In the python backend:

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健全性检查不起作用-我不知道为什么:

In the JavaScript (note that the console.log sanity checks don't work - I have no idea why:

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返回引起的问题),我已经解决了多功能回调问题我一路发现.但是,我现在从complete textStatus中获得了parsererror.我认为问题出在Python/Flask(请参阅下面的当前代码).再次感谢所有帮助过的人!

With help from the advice below, I'm pretty close to having this off the ground. The JSON is no longer printing to the screen (an issue caused by the Flask return), and I've solved a multifunction callback issue I discovered along the way. However, I am now getting a parsererror from the complete textStatus. I think the problem now lays in the Python/Flask (see current code below). Thanks again for all who've helped!

Python/Flask(我想问题出在这里-我对Flask不满意):

Python/Flask (I think the problem is here - I'm a noob to 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对象返回-用于解决回调问题)

The JavaScript (the data is returned by the Deferred object - used to solve a callback issue):

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
};

推荐答案

事实证明,我上面的代码中有很多问题,其中一些我必须在相关问题中进行调试此处.

It turns out I had a lot of problems in my code above, several of which I had to debug in related questions here and here.

其中有:

  • 在我最初的Flask index()函数中,它是将JSON数据转储到屏幕上,因为我没有在任何地方渲染index.html模板.
  • 我在Flask函数中具有匹配的路由('/')和函数名称(index())
  • 如评论中所述,我使用dataType: jsonarray_data = JSON.parse(JSON_array)
  • 对JSON进行了不必要的双重解析
  • 这个异步函数的返回总是不确定的,因为在调用解决之前就已经引用了它
  • 在以后更新为Deferred对象时,success属性应显示为:success: function(data) { deferredData.resolve(data);}
  • in my original Flask index() function, it was dumping the JSON data to the screen because I was not rendering the index.html template anywhere.
  • I had matching routes ('/') and function names (index()) in the Flask functions
  • As mentioned in the comments I did an unnecessary double parsing of the JSON with dataType: json and array_data = JSON.parse(JSON_array)
  • the return from this asynchonous function always came up undefined because it was referenced before the call had resolved
  • in my later update to a Deferred object, the success property should have read: success: function(data) { deferredData.resolve(data);}

因此,在完成所有这些修复之后,下面是起作用的代码!

So, after all those fixes, here is the functioning code!

烧瓶/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()函数)

JavaScript: (note: this is the foo() function in my question above)

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);    
});

这篇关于从Python(Flask)传递到JavaScript的JSON显示在屏幕上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆