我有一个网站(使用jquery bbq
),其中会触发ajax请求,并在收到响应时替换正文中某处的div
。大致如下:
var mainContent = $('#main_content');
if ( cache[ url ] ) {
mainContent.fadeOut(duration, function() {
mainContent.html(cache[ url ]);
mainContent.fadeIn(duration, function() {
$(document).trigger("ajax_loaded");
});
});
} else {
mainContent.fadeOut(duration, function() {
var postAjaxCallback = function() {
cache[ url ] = mainContent.html();
$(document).trigger("ajax_loaded");
};
$('#loading').fadeIn(duration, do_ajax(url, duration, postAjaxCallback));
} );
}
function do_ajax(linkVal, duration, callback) {
$.ajax({
type: "GET",
url: linkVal,
dataType: "html",
success: function(page){
var mainContent = $('#main_content');
mainContent.stop(true, true);
if(parseInt(page)!=0)
{
mainContent.html(page);
$('#loading').fadeOut(duration, function() {
mainContent.fadeIn(duration, callback);
} );
}
}
});
}
现在总的来说,这效果很好。主页是这样的:
<html>
<head>
...
</head>
<body>
<div id="main_content");
<p>Hello world!</p>
</div>
/body>
</html>
#page2
的 ajax 返回类似于
<p>Hello to a different world!</p>
在#page3
上,情况变得有点复杂。 ajax返回的内容为:
<script type="text/javascript">
function initialize() {
var mapOptions = {
zoom: 11,
streetViewControlOptions: true,
center: new google.maps.LatLng(26.737792, 49.878273),
mapTypeId: google.maps.MapTypeId.SATELLITE
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
}
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=initialize";
document.body.appendChild(script);
}
loadScript();
$(document).bind("ajax_loaded", function() {
console.log("map resize called");
google.maps.event.trigger(map, 'resize');
});
</script>
现在第一次加载 #page3
时,一切正常,控制台日志触发并且 map 大小被调整(由于灰色区域问题需要调整大小)。现在我想要发生的是所有其他页面继续正常加载(通过ajax调用或从缓存),并且当再次导航到#page3
时(即 #("main_content")
是从缓存中设置的,调整大小事件再次触发。我想用最简单的术语来说,我正在尝试创建一个在每个 ajax 页面后触发的事件已加载,我可以在每个 ajax 检索页面上有一个自定义 $(document).bind("ajax_loaded", function() {});
,它可以执行我需要的任何后处理。
当前表现出的行为是,在加载 #page3
之前不会发生任何事情(正如我提到的, map 已调整大小,一切都很顺利)。之后,每个页面加载都会触发绑定(bind)函数并打印到控制台(我猜这是合理的,因为我已将其绑定(bind)到 $(document)
,是否有更好的方法可以使其对每个页面都唯一?)但是,真正的痛苦是,当我尝试重新加载 #page3
时, map 会加载但不会调整大小(控制台仍会打印),因此 map 上有灰色区域。
任何人都可以帮助我以我有限的 javascript 经验来获得正确的工作流程。重申一下:
- 每个ajax加载(或从缓存加载)都会触发一些事件
- 在每个 ajax 页面(
#page1
、#page2
等)中,都会有一个从上述步骤触发的函数,该函数可以对每个 ajax 进行唯一的设置页。
感谢您的帮助!
编辑 我尝试过使用以下内容:
mainContent.find("script").each(function(i) {
eval($(this).text());
});
而不是触发ajax_loaded
事件但无济于事。我还可以尝试什么吗?
最佳答案
我相信,当第二次添加 Google Maps API 时(重新加载 #page3
),一切都会搞砸。它会导致一些错误,并且脚本的其余部分可能会停止工作。尝试包装加载将 Google Maps API 转换为条件 if (typeof google === 'undefined') { ...
。
但说实话,整个概念可能需要一些重构:)。
关于javascript - 谷歌地图加载ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14591455/