這是我的問題。 我有外部文件include.html,我加載$ .ajax並追加到正文。 內容include.html的:JS如何在使用ajax後獲得嵌入元素的值
<p id="descriptionText">My description</p>
我想阿賈克斯完成後才能計算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
參數它的工作原理,但我需要異步準確。我的問題是什麼?謝謝!
您不等待$ .ajax完成通話。您可以嘗試進行自定義回調。 –
可能的重複[如何返回來自異步調用的響應?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) –
或http://stackoverflow.com/questions/9466241/selecting-dom-elements-after-html-was-inserted-in-a-page-with-ajax –