gpt4 book ai didi

javascript - JS如何在使用ajax后获取嵌入元素的值

转载 作者:行者123 更新时间:2023-11-29 16:07:05 25 4
gpt4 key购买 nike

这是我的问题。我有外部文件 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());进入.done() $.ajax() 的回调

喜欢:

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

解释:

.done()是解决 promise 时的成功回调。异步领域中的 promise 意味着代码将在比当前时钟滴答更晚的时间点执行。你的console.log此时执行,因此始终未定义,因为 promise 尚未解决。

所以,soln 就是要注意你的 console.log在 promise 已解决后执行。以多种可能的方式做到这一点,一个简单的方法就像我之前提到的:将语句移动到 .done() 中。在你执行了 .html() 之后DOM 操作。

关于javascript - JS如何在使用ajax后获取嵌入元素的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38753596/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com