2

我的网站上有一个页面,其中包含两个内容,需要大约 10 秒的时间来计算。我不想让用户在页面加载之前等待这么久。我想加载没有内容的页面,然后使用 ajax 发送请求 onwindow load 以计算这些内容,然后将它们添加到内容中。在此之前,装载圈是完美的。问题是我之前没用过ajax,感觉很迷茫。 编辑1:

我尝试尝试使用 jquery 和 ajax。我做了一些事情,但我有一个错误。

HTML 代码:

<div id="image" class="span3">
<script type="text/javascript">
    $(function jqueryonload() {
        $.getJSON('/_jqueryonload',{

        "links": {{links}} #links is a jinja variable I pass on render and I want to use it again
        }, 

        function(data) {

          $("#image").html(data.image);

        });
        return false;
        });

        window.onload = jqueryonload;
 </script>

这是烧瓶代码:

@app.route('/_jqueryonload')
def jqueryonload():

    links = request.args.get('links')
    image_v = image_def(links) # this is a function that find the link of the image

    image = '''<img src="%s"/>''' % (image_v)

    return jsonify(image=image)

我不知道问题是什么,但图像根本不显示:(

4

1 回答 1

0

您显然没有将任务对象传递给模板,这就是您不能使用它的原因。我没有用过烧瓶,但你可能会通过tasklinks作为一个字典逃脱。

return render_template("task_details.html", {'links': links, 'task': task))

这是一个使用bottlepy和ajax的例子,和flask很相似

阿贾克斯调用:

$.ajax(url: '/methods/12',
type: json, 
data: somedata,
success: function(result){
alert(result);
});

Python:

@route('/methods/<id>', method='GET')
def getUserStatus(id='0'):
    # Get user status info
    try:

        con = pymysql.connect(user=dbUser, passwd=password, host=dbHost, port = dbPort, db=database)
        cursor = con.cursor()
        status = cursor.execute("SELECT account_number,account_type FROM payment_methods")
        status = cursor.fetchall()
        con.close()
    # handle mysql errors   
    except pymysql.Error as error2:
        message = ({"result":"error","error_name":error2[1]})
        return json.dumps(message)
    # Preparing response
    q = len(status)
    columns = zip(*status)
    acc_n  =columns[0]
    acc_t = columns[1]
    #acc_n = [x for (x,y) in status]
    #acc_t = [y for (x,y) in status]
    message = ({"result":"OK","q":q,"acc":acc_n,"name":acc_t})
    # Return
    return json.dumps(message)
于 2013-11-13T22:24:58.997 回答