【发布时间】:2016-04-13 04:38:42
【问题描述】:
我正在通过 ajax get 将内容加载到一个 div 中,我有 3 个页面:
索引 通过ajax加载的动态内容 javascript.js
现在当我通过以下方式将数据加载到索引中时:
$.ajax({
url: target,
type: 'GET',
}).done(function(data)
{
$(".modal-content").html($(data).find('.inner_modal'));
$(".modal-header").prepend('<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>');
});
});
即使我在主索引中包含了 javascript 文件,javascript 也无法使用它。
我试过这样绑定:
$(function()
{
$('.inner_modal').on("submit", "#account-login-form", function()
{
$('.ajloading').show();
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
dataType: 'json',
data: $(this).serialize(),
success: function(data)
{
if(!data.success)
{
$('#error_message').html(data.error + alert_close).show();
}else{
<?php if(Session::get('refer') == true && Session::get('refer') != 'user/logout'): ?>
window.location.href = '<?php echo Config::get('URL'); ?><?php echo System::escape(Session::get('refer')); ?>';
<?php else: ?>
window.location.href = '<?php echo Config::get('URL'); ?>dashboard';
<?php endif; ?>
}
$('.ajloading').hide();
}, error: function(data)
{
$('.ajloading').hide();
}
});
return false;
});
});
我试过这样:
$(document).on("submit", "#account-login-form", function()
我也试过没有
$(function(){});
现在,当我在动态加载的内容中取消包含 javscript 文件时,它可以工作,但我不能对每个文件都这样做,而且它会使我的脚本膨胀,所以我该如何解决这个问题,以便动态内容与我的主要内容一起工作js 文件....这是我的做法:
<body>
<div class="modal-content">
<!-- dynamic content loaded !-->
</div>
</body>
<script>
$.ajax({
url: target,
type: 'GET',
}).done(function(data)
{
$(".modal-content").html($(data).find('.inner_modal'));
$(".modal-header").prepend('<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>');
});
});
</script>
<script src="myjs.js"></script>
</html>
【问题讨论】:
-
“不工作”是什么意思——是代码渲染到页面而不是“触发”——还是没有渲染到页面?您是否在控制台中遇到任何错误?另外,请查看之前的答案:stackoverflow.com/questions/3619484/…
-
defering你的脚本怎么样? async vs defer -
@timster 它没有触发,但它在我的主脚本的页脚中,所以它在那里并且没有控制台错误。
-
PHP 代码在那里做什么?这实际上会在发送到浏览器的 JavaScript 中吗?如果是这样,那将不起作用,因为服务器永远不会解释 PHP。 (您是否检查过您的 HTML 中是否存在未解释的 PHP?)
标签: javascript jquery