如何将多个 Ajax 调用合并为单个代码片段?



我们有这个代码:

<!-- Module 1 -->
<div class="module-1">
<script type="text/javascript"> <!-- here we call content from Page 1 -->
$.ajax({
url: "https://thewebsite.com/page1.html",
type:'GET',
success: function(data){
$('.content-1').html($(data).find('.text').html());
}
});
</script>
<div class="content-1"></div>
</div>
<!-- Module 2 -->
<div class="module-2">
<script type="text/javascript"> <!-- here we call content from Page 2 -->
$.ajax({
url: "https://thewebsite.com/page2.html",
type:'GET',
success: function(data){
$('.content-2').html($(data).find('.text').html());
}
});
</script>
<div class="content-2"></div>
</div>
<!-- etc -->

我不知何故怀疑可以使用对所有"模块"的单个通用 Ajax 调用来改进这一点,但我不知道如何编写它。

谁能帮忙?

当然,您可以创建一个共享函数并从模块中调用它。看起来你有一个普通的HTML页面,所以你只需要创建一个通用的load函数,然后从你的模块调用它。

<!-- shared code -->
<script>
function loadPage(url, success) {
$.ajax({
url: url,
type:'GET',
success: success
});
}
</script>
<!-- Module 1 -->
<div class="module-1">
<script type="text/javascript"> <!-- here we call content from Page 1 -->
loadPage('https://thewebsite.com/page1.html', function(data){
$('.content-1').html($(data).find('.text').html());
});
</script>
<div class="content-1"></div>
</div>
<!-- Module 2 -->
<div class="module-2">
<script type="text/javascript"> <!-- here we call content from Page 2 -->
loadPage('https://thewebsite.com/page2.html', function(data){
$('.content-2').html($(data).find('.text').html());
});
</script>
<div class="content-2"></div>
</div>
<!-- etc -->

请注意,这种方法并不是最好的,因为它会污染全局命名空间,但您可以使用现有内容。将现代 JavaScriptimport与模块捆绑器(如 WebPack(相结合,可以帮助您进一步组织 JavaScript 代码。如果您还不熟悉,请查看它们。

相关内容

最新更新