我目前正在使用3个不同的.load()
来电加载同一页3次。我想知道我能对optimize
代码做些什么。
当我点击目前的链接时,它会加载页面3次
$("#"+target).load(url + " #page", function(response, status, xhr){
if(status === "error")
{
$("#"+target).load('error.php?error=503 #page', function(response, status, xhr){
if(status === "error")
{
alert("Something has gone very wrong right now, please contact an admin quoting 'error.php'");
return;
}
}); // This should never fail but if it does kill the page
console.log('Content failed to load ' + xhr.status + ' ' + xhr.statusText);
//Force update the title to error
document.title = "Error";
$("#pageBreadcrumbs").load('error.php #breadcrumbs');
}
else
{
console.log('Content was loaded');
//Load the title dynamically
document.title = "Venus | " + name;
$("#pageBreadcrumbs").load(url + ' #breadcrumbs');
if(sidebar === true)
$("#pageSidebar").load(url + ' #sidebar');
}
无论如何,我可以将此缩短为仅调用一个url或错误页面并从那里提取它吗?
答案 0 :(得分:0)
您可以使用此代码:
$.get(url, function(response) {
var $nodes = $(response);
... some conditions ...
var $container1 = $("#"+target).html('');
$nodes.find('#page').appendTo($container1);
... some conditions ...
var $container2 = $("#pageBreadcrumbs").html('');
$nodes.find('#breadcrumbs').appendTo($container2);
});
我不确定它是否有效,但你可以尝试一下......
<强>更新强>
此代码假定整个服务器响应包含在一个容器(div)
中