未定义的结果从延期的AJAX请求到Flask [英] Undefined result from Deferred AJAX request to Flask

查看:143
本文介绍了未定义的结果从延期的AJAX请求到Flask的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Flask和AJAX的新手,目前的挑战是当我向服务器发出一个AJAX请求时,我的结果是 undefined 。我使用延迟对象来跟踪几个异步请求,除了下面显示的AJAX函数,所有的工作都正常。另外两个是非AJAX。 以下代码中的可能问题区域标有 >>>>



对于上下文,我正在将后端写入浏览器中的单页动画。无论观看者有什么请求(点击)或动画以自己的方式编程(定期添加和减去视觉材料),该模板都保持不变。

Flask / Python:

  from flask import Response,json,render_template 
from app import app
from motifs import 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

  function getData(){

var deferredData = new jQuery.Deferred();

$ .ajax({
类型:GET,
url:/,
dataType:json,//>>> ;>当我注释掉了,我得到一个错误,当我离开它我得到一个parsererror
成功:deferredData.resolve(),
完成:function(xhr,textStatus){
console.log(AJAX REQUEST complete - >,xhr, - >,textStatus);
}
});

return deferredData; //包含传递的数据>>>>目前未定义的!
};


// DEFERRED OBJECTS
//用于在多个异步函数之后执行回调
var deferredData = getData();
var deferredWindow = windowLoaded();
var deferredImages = loadImages();


//在多个异步函数之后进行单次回叫
$ .when(deferredWindow,deferredData,deferredImages).done(function(window,data,images){
console.log(window has loaded - + window); //成功!
console.log(data is:+ data); //>>>> undefined!
console.log(图像是:+图像); //成功!
});

更新:

感谢@Jason P getData AJAX调用的成功函数现在是 success:function(data){deferredData.resolve(data) ; } ,结果不再是 undefined !唉,这也不是我的数据。我想我可能有一个错误(或概念误解)在我的Flask代码,因为请求返回我的HTML模板,而不是我的JSON数据的完整文本。想法?



更新2

另外@Jason P的建议我改变了路线在Flask中的URL和AJAX请求到一个替代路由: / ajax ,以避免潜在的(?!)与模板渲染的冲突。但是,请求仍然返回我的HTML模板的全文。也许我也需要区分python / flask函数名称? ...将尝试下一步。


$ b

Python / Flask:

c $ c> @ app.route('/ ajax')
def index():
motifs = get_motif_list(10)
响应(json.dumps(motifs),mimetype ='应用程序/ json')

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

JavaScript AJAX url属性更改为:
url:'/ ajax' $ b

UPDATE 3



我区分了python / flask函数名因此 / ajax 路由函数现在称为 ajax(),并且根路由 '/'函数仍然被称为 index()。现在,JSON对象呈现给屏幕(而不是作为变量传递),而且没有任何东西从JavaScript呈现(大概现在缺少模板呈现?)

已解决



在@Jason P的评论之后,这个调用终于被解决了。 Wheew!这是最后的代码:

Flask / Python

  import响应,json,render_template 
从应用程序导入应用程序
从motifs导入get_motif_list

@ app.route('/ ajax')
def ajax():
motifs = get_motif_list(10)
返回响应(json.dumps(motifs),mimetype ='application / json')

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

JavaScript :

$ p $ function getData(){

var deferredData = new jQuery.Deferred();

$ .ajax({
类型:GET,
url:/ ajax,
// dataType:json,
成功:函数(数据){
deferredData.resolve(数据);
},
错误:函数(数据){
调试器;
警报(错误 );
},
complete:function(xhr,textStatus){
console.log(AJAX Request complete - >,xhr, - >,textStatus);
}
});

return deferredData; //包含传递的数据
};

//脚本中的所有其他内容与上面相同...

感谢!

解决方案



  success:deferredData.resolve()



立即执行 ()



试试这个:

  success:function(data){deferredData.resolve(data); } 


I'm new to Flask and AJAX and my current challenge is that when I make an AJAX request to the server my result is undefined. I am using deferred objects to keep track of several asynchronous requests, and all are working except for the AJAX function shown below. The other two are non-AJAX. Likely problem areas in the code below are marked with >>>>

For context, I am writing the backend to a one-page animation in the browser. The template remains the same regardless of any requests (clicks) from the viewer or any data requests the animation makes on its own programmatically (periodic adding and subtracting of visual material).

Flask/Python:

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

# >>>> can/should I use two functions aimed at the same route? Not sure how to both render the template and pass data
@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:

function getData() {

    var deferredData = new jQuery.Deferred();

    $.ajax({
        type: "GET",
        url: "/",
        dataType: "json", // >>>> when I comment this out I get an error, when I leave it in I get a parsererror
        success: deferredData.resolve(),
        complete: function(xhr, textStatus) {
            console.log("AJAX REquest complete -> ", xhr, " -> ", textStatus);
            }
    });

    return deferredData; // contains the passed data >>>> currently undefined!!!
};


// DEFERRED OBJECTS
// used to perform a callback after multiple asynchronous functions
var deferredData = getData();
var deferredWindow = windowLoaded();
var deferredImages = loadImages();


// SINGLE CALLBACK AFTER MULTIPLE ASYNCHRONOUS FUNCTIONS
$.when( deferredWindow, deferredData, deferredImages  ).done( function( window, data, images ) {
    console.log("The window has loaded - " + window); // successful!
    console.log("The data are: " + data); // >>>> undefined!
    console.log("The images are: " + images); // successful!    
});

UPDATE:

Thanks to @Jason P the success function in the getData AJAX call is now success: function(data) { deferredData.resolve(data); } and the result is no longer undefined! Alas, it's not my data, either. I think I may have a bug (or a conceptual misunderstanding) in my Flask code because the request returns the complete text of my html template instead of my JSON data. Thoughts?

UPDATE 2

Also @Jason P's suggestion I changed the route url in Flask and the AJAX request to an alternate route: /ajax to avoid a potential(?!) clash with the template rendering. However, the request still returns the full text of my html template. Perhaps I also need to differentiate the python/flask function names? ...will try that next. Updated code below.

Python/Flask:

@app.route('/ajax')
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 AJAX url property changed to: url: '/ajax'

UPDATE 3

I differentiated the python/flask function names so that the /ajax route function is now called ajax(), and the root route '/' function is still called index(). The JSON object now renders to the screen (instead of being passed in as a variable) and nothing from the javascript renders (presumably now missing the template rendering?)

RESOLVED

Following on comments by @Jason P the call is finally resolved and functioning. Wheew! Here is the final code:

Flask/Python

from flask import Response, json, render_template
from app import app
from motifs import 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:

function getData() {

    var deferredData = new jQuery.Deferred();

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

    return deferredData; // contains the passed data
};

// all else in the script remains the same as above...

Thanks!

解决方案

This line:

success: deferredData.resolve()

Immediately executes resolve().

Try this instead:

success: function(data) { deferredData.resolve(data); }

这篇关于未定义的结果从延期的AJAX请求到Flask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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