通过 ajax 获取返回值

Getting a return value via ajax

本文关键字:返回值 获取 ajax 通过      更新时间:2023-09-26

我有一个python脚本,我使用按钮和一些带有ajax的javascript从表单中调用它。我真的很难找到 python 脚本返回的返回变量。

返回的信息似乎都以错误的顺序发生,可能不是这样,但在我看来是这样。我想要的只是能够获取我的python脚本返回的数据。这么简单的事情怎么会这么难!!

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

这是我的代码:

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

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

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

克里斯

编辑。

    <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:

import MySQLdb

定义指数(要求): 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)

这就是异步编程的本质。它是非阻塞的。您必须启动需要在回调中response的代码的执行。

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

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

编辑

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

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

例如,在页面加载时。一次。很清楚你想如何触发它。如果单击按钮,并且按钮id为"按钮",则<button id="button">click</button>

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

执行链 :

  1. 称为绘图图的东西
  2. 绘制
  3. 图调用绘制并传递回调函数
  4. 在 AJAX 成功时,使用响应调用回调函数

因为javascript是异步的,所以你必须"等待"才能"继续处理其余的代码",最好的方法是从$.ajax成功内部继续执行。

Ajax 中的 "A" 是异步的。 这意味着 HTTP 请求已完成,其余的 JS 代码将执行。 您不能依赖于请求何时完成,甚至不能依赖于请求是否完成。 任何依赖于从请求返回的值的工作都必须在回调中完成(success

function (response) {
    alert("Success");
    // this will alert the response
    alert(response);
}

此外,来自回调的return不会去任何地方。 你也不会从draw回来。

您可以使用延迟使语法更可口:

function drawgraph() {
    var x = draw();
    x.done(function (response) {
        alert(x);
    });
}
function draw() {
    return $.ajax(/* your code */