Ajax对象向后台请求数据设置为异步结果是Undefined

我在使用Ajax向后台请求数据时结果为Undefined

正常应该是我点击按钮之后浏览器执行Ajax的回调函数,向我返回数据啊,为什么我的数据时Undefined啊,请CSDN大佬帮忙解决一下,谢谢!

HTML代码

<body>
    <button id="submit">点击</button>
</body>
</html>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="../static/js/t.js"></script>

JavaScript代码

$("#submit").click(function(){
    let jsons= {"data": "Hello"}
    const result = Ajax(jsons, '/app');
    console.log(result.responseJSON); // 此处返回结果为Undefined,如果此时在浏览器console再次调用Ajax函数,数据则会正常返回回来
});

function Ajax(data, path) {
    return $.ajax({
        async: true, // 设置为异步调用
        type: 'post',
        url: path,
        cache: false,
        contentType: 'application/json;charset=utf-8',
        data: JSON.stringify(data),
        dataType: 'json',
        success: function (data) {

        },
        error: function () {
            alert("请求失败")
        }
    })
}

后端Python代码

@app.route("/app", methods=["POST", "GET"])
def test():
    data = {"13": 123}
    return json.dumps(data);

app.run()

ajax 默认的请求方式是异步的,你需要去了解下ajax异步的概念
异步加载的内容,不能用return返回值,一定必须要学会使用回调函数。
要把所有加载之后的后续操作都放到回调函数中。
你题目的解答代码如下:

$("#submit").click(function(){
    let jsons= {"data": "Hello"}
    Ajax(jsons, '/app', function (result) {
        console.log(result.responseJSON); // 把所有加载之后的后续操作都放到回调函数中。
    });
});
 
function Ajax(data, path, callback) {
    return $.ajax({
        async: true, // 设置为异步调用
        type: 'post',
        url: path,
        cache: false,
        contentType: 'application/json;charset=utf-8',
        data: JSON.stringify(data),
        dataType: 'json',
        success: function (data) {
            callback(data);
        },
        error: function () {
            alert("请求失败")
        }
    })
}

如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!

img

你后端能否收到ajax的请求

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632