通过ajax获取返回值 [英] Getting a return value via ajax

查看:86
本文介绍了通过ajax获取返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个python脚本,我正在使用按钮和带有ajax的javascript从表单中调用该脚本.我真的很难到达python脚本返回的返回变量.

I have a python script which I'm calling from within a form using a button and some javascript with ajax. I'm really struggling to get to the returned variable which the python script returns.

所有返回的信息似乎是按错误的顺序发生的,可能不是这种情况,而是它对我的外观.我想要的只是能够获取python脚本返回的数据.如此简单的事情怎么会如此困难!

The information which is getting returned all seems to be happening in the wrong order, which is probably not the case but its how it looks to me. All I want is to be able to get the data which my python script returns. How can something so simple be so hard!!

任何帮助将不胜感激.谢谢

Any help will be appreciated. Thanks

这是我的代码:

            <script>
            function drawgraph() {
                    var x = draw()
                    alert(x)
            };
            </script>
            <script>
            function draw() {
                    alert("Hello");
                    $.ajax({
                            url: "/currentcost.py",
                            success: function(response){
                            alert("Success");
                            return response;
                            //here you do whatever you want with the response variable
                            }
                    });
                    alert("World");
            }
            </script>

我得到的答复是你好",世界",未定义"和成功"

The responses I get are "Hello", "World", "Undefined" and "Success"

这对我说ajax函数实际上直到我的javascript函数完成后才真正完成,这实际上并不能帮助我真正掌握返回的变量,因此以后可以在javascript中使用它

This says to me the ajax function isn't actually completing until AFTER my javascript function has finished which doesn't help me actually get hold of the returned variable so I can use it in the javascript later on

克里斯

编辑.

    <head>
            <title>Line Chart</title>
            <script>
            var ajaxResponse = ""
            </script>
            <script src="Chart.js"></script>
            <script src="jquery.js"></script>
            <script>
                    function drawgraph() {
                            function handleResponse(response) {
                                    ajaxResponse = response;
                            }
                            draw(handleResponse);
                    };

                    function draw(handleResponse) {
                    $.ajax({
                    url: "/currentcost.py",
                    success: function(response){
                            handleResponse(response);
                    }
                    });
            }
            </script>
            <script>
                    function alertbox() {
                            alert(ajaxResponse);
                    }
            </script>

Currentcost.py:

Currentcost.py:

导入MySQLdb

def index(req):dtbox = req.form.getfirst('dt','')tmbox = req.form.getfirst('tm','')

def index(req): dtbox = req.form.getfirst('dt', '') tmbox = req.form.getfirst('tm', '')

con = MySQLdb.connect('localhost', 'root', '', 'mydb')

with con:
    cur = con.cursor(MySQLdb.cursors.DictCursor)
    s = "SELECT tmp, watts FROM currentcost WHERE dt ='" + dtbox + "' and tm like '" + tmbox + "%'"
    cur.execute (s)
    rows = cur.fetchall()

    x=""
    y=""
    for row in rows:
        x=x+row["watts"]+","
        y=y+row["tmp"]+","

x="data:["+x+"]"
y="data:["+y+"]"

con.close()

req.write(x)

推荐答案

JavaScript是异步的.当您警告 x 时,很可能是 undefined ,因为尚未收到ajax响应,或者甚至没有启动ajax.传递一个可以处理响应的回调函数,而不是返回它:

Javascript is asynchronous. When you alert x it will most likely be undefined because the ajax response is not received yet, or ajax is not even started. Pass a callback function that can handle the response, instead of returning it :

//global variable holding the response
//substitutes your x
var ajaxResponse;

function drawgraph() {
    function handleResponse(response) {
        ajaxResponse = response; 
        //here you may want to do something with the response
        //like calling a function that uses the global variable ajaxResponse

        //alert(response);
    }
    draw(handleResponse);
};

function draw(handleReponse) {
    $.ajax({
       url: "/currentcost.py",
       success: function(response){
           handleResponse(response);
       }
    });
}

编辑

在我的小测试中,我只是在

Edit

In my little test I just called drawgraph in a

$(document).ready(function() {
  drawgraph();
}

例如,页面加载时.一次.您不清楚如何触发它.如果单击按钮,并且按钮 id 是"button",则< button id ="button"> click</button>

Eg, on page load. Once. It was onclear how you wanted to trigger it. If click on a button, and the button id is "button", <button id="button">click</button>

$('#button').click(function() {
  drawgraph();
}

执行链:

  1. 某事叫drawgraph
  2. drawgraph调用draw并传递一个回调函数
  3. 成功执行ajax时,将在响应中调用回调函数

由于javascript是异步的,因此必须等待",然后才能继续进行其余的代码",并且最好的方法是从$ .ajax成功内部继续执行.

Because javascript is asynchronous, you have to "wait" before you can "carry on with the rest of the code", and the best way is to continue execution from inside $.ajax success.

这篇关于通过ajax获取返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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