JS如何在使用ajax后获得嵌入元素的值

JS How to get value of embeded element after using ajax

本文关键字:元素 ajax JS      更新时间:2023-09-26

这是我的问题。我有一个外部文件include.html,我用$.ajax加载并附加到正文中。include.html的内容:

<p id="descriptionText">My description</p>

我想在ajax完成后获得p#descriptionText的值,但结果我看到了"未定义"的

<!DOCTYPE html>
<html lang="en">
<head>    
<meta charset="UTF-8">
    <title>AJAX</title>
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"
            integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
    <script>
        $(document).ready(function () {
            $.ajax({
                url: "include.html",
                dataType: "html",
            }).done(function (response) {
                $('body').html(response);
            });
            console.log($('#descriptionText').val());
        });
    </script>
</head>
<body>
</body>
</html>

即使我尝试使用闭包,结果也是一样的。以下示例。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>AJAX</title>
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"
            integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
    <script>
        function func() {
            $.ajax({
                url: "include.html",
                dataType: "html",
            }).done(function (response) {
                $('body').html(response);
            });
            return function() {
                console.log($('#descriptionText').val());
            }
        }
        func()();
    </script>
</head>
<body>
</body>
</html>

如果我在$.ajax中使用async: false参数,它可以工作,但我需要完全异步。我的问题是什么?非常感谢。

简而言之:将console.log($('#descriptionText').val());移动到$.ajax().done()回调中

类似:

.done(function (response) {
    $('body').html(response);
    console.log($('#descriptionText').val());
});

解释:

.done()是解决承诺时的成功回调。异步区中的promise意味着代码将在当前时钟点之后的某个时间点执行。您的console.log此时已执行,因此将始终未定义,因为承诺尚未解决。

因此,soln需要注意在承诺得到解决后执行console.log。可以通过多种可能的方式来实现这一点,其中一种简单的方式就像我前面提到的:在执行了.html()DOM操作之后,在.done()中移动语句。

您扰乱了异步流。将输出移动到异步回调中。像这样:

$(document).ready(function () {
    $.ajax({
        url: "include.html",
        dataType: "html",
    }).done(function (response) {
        $('body').html(response);
        console.log($('#descriptionText').val());
    });
});

这个问题确实与异步代码执行有关。此行:

        console.log($('#descriptionText').val());

在之前执行此操作执行:

            $('body').html(response);

这是因为您提供给.done的回调函数是异步执行的,当收到Ajax响应时,JavaScript正在读取事件队列,以查看接下来要执行什么。但只有当当前执行的代码完成时(即调用堆栈被清空),才会发生这种情况。

所以。。。要解决这个问题,您必须将代码移动到done回调:中

        }).done(function (response) {
            $('body').html(response);
            console.log($('#descriptionText').val());
        });

因此,将响应附加到主体的回调是代码中等待请求完成的唯一部分。因此该函数是用CCD_ 13定义的。

如果你像这样把代码添加到这个函数中,它就会起作用。

.done(function (response) {
    $('body').html(response);
    console.log($('#descriptionText').val());
});