jquery ajaxをいくつか実行しようとしていますが、特定のコンテンツをロードする正しい方法を知りたいと思います。私の場合は、私が望むものがロードされる "メイン"のIDを持つdiv内のコンテンツであるとき、私の与えられた領域内のHTML文書全体をロードしています。ここでjQuery AJAX - 文書全体を読み込まない
はコードです:
(function($){
// target the links
$link = $('nav a');
// on click
$link.on('click', function(event){
// create variables
$el = $(this);
var value = $el.attr("href");
event.preventDefault();
$.ajax({
url: value,
method: 'POST',
data: { href: value }
})
.done(function(html) {
$("#main").append(html);
});
});
})(jQuery);
そして、ここではHTMLです:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>AJAX jQuery</title>
<meta name="description" content="">
<meta name="author" content="">
<!-- Mobile Specific Meta -->
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"/>
<!-- Stylesheets -->
</head>
<body>
<nav>
<a href="/ajax-test">Main</a>
<a href="external.html">Some link</a>
</nav>
<div id="main">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
<script src="https://code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script>
<script src="ajax.js" charset="utf-8">
</script>
</body>
</html>
私はexternal.htmlのコンテンツをロードする代わりに、それは等を含めた文書全体をロードします。
あなたの助けをありがとう!
へのHTMLオーバーヘッドを入れていない、バックエンド側を変更します:http://stackoverflow.com/questionsを/ 405409/use-jquery-selector-on-ajax-loaded-html –