2016-08-03 23 views
2

這是我的問題。 我有外部文件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參數它的工作原理,但我需要異步準確。我的問題是什麼?謝謝!

+0

您不等待$ .ajax完成通話。您可以嘗試進行自定義回調。 –

+0

可能的重複[如何返回來自異步調用的響應?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) –

+0

或http://stackoverflow.com/questions/9466241/selecting-dom-elements-after-html-was-inserted-in-a-page-with-ajax –

回答

3

簡而言之:移動console.log($('#descriptionText').val());.done()回調$.ajax()

像:

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

說明:

.done()是承諾解決時的成功回調。異步域中的承諾意味着代碼將在比當前時鐘更晚的時間點執行。您的console.log此時執行,因此始終未定義,因爲承諾尚未解決。

因此,soln應注意,您的console.log在承諾解決後執行。以許多可能的方式做到這一點,就像我之前提到的那樣:在執行.html() DOM操縱後,將該語句移動到.done()之內。

1

你搞亂了異步流程。將輸出移動到異步回調。像這樣:

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

該問題確實與異步代碼執行有關。這條線:

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

...執行在此之前執行:

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

那是因爲你提供了.done回調函數是異步執行的,當收到Ajax響應, JavaScript正在讀取事件隊列以查看它必須執行的操作。但是,這隻會在當前正在執行的代碼完成時(即調用堆棧清空)發生。

所以......要解決這個問題,你必須將你的代碼done回調中:

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

因此,將響應附加到正文的回調是代碼中等待請求完成的唯一部分。因此該功能被定義爲.done(...)

如果你將代碼添加到這個函數就可以了。

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