如何在ajax请求后重新加载所有javascript?
我有一个包含很多 JavaScript 的页面。 我有内容并且它有 javascript 效果。我想使用ajax将内容更改为另一个内容(当然具有相同的javascript效果)。
这是我的 ajax 请求代码:
<head>
<script type="text/javascript">
function ajax(txt) {
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("MICROSOFT.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 & xmlhttp.status==200)
{
document.getElementById("content").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", "index.php?p="+txt, true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="content">
...content...
</div>
<input type="button" onclick=ajax('2') value="click" />
</body>
问题是内容已更改,但新内容没有任何 javascript 效果。 我认为 javascript 需要重新加载,但是在 ajax 请求之后我该怎么做呢?
谢谢
I have a page with a lot of javascripts.
I have content and it has javascript effects. I want to change the content to another content (Of course with the same javascript effects) using ajax.
Here is my code for ajax request:
<head>
<script type="text/javascript">
function ajax(txt) {
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("MICROSOFT.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 & xmlhttp.status==200)
{
document.getElementById("content").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", "index.php?p="+txt, true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="content">
...content...
</div>
<input type="button" onclick=ajax('2') value="click" />
</body>
The problem is the content is changed but the new content doesn't have any of the javascript effects.
And I think the javascripts need to be reloaded but how can I do it after an ajax request?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不必重新加载 JavaScript 文件。你所要做的就是让“效果”知道你的页面上有新内容。通常你必须再次运行一个函数。如果使用 jquery 函数是 $(document.ready(...))。如果您的“效果”未包装在函数中,则将它们包装起来并在内容更改时调用此函数。
You do not have to reload your javascript files. All you have to do is to make "effects" know that there is new content on your page. Usually you have to run again a function. In case of using jquery function is $(document.ready(...)). If your "effects" aren't wrapped in a function than wrap them and call this function when content is changed.
如果重新加载 Javascript 文件是解决方案,您可以尝试此功能:
并使用它:
或者如果您想在加载文件时触发操作,请使用回调函数:
If reloading the Javascript files is the solution, you can try this function:
And to use it:
or use the callback function if you want to trigger an action when the file is loaded:
在新旧
content
块中包含用于效果的 JavaScript,并在插入新节点后重新运行效果脚本,如下所示:另外,以某种方式从
head
删除旧脚本也是个好主意如果你计划了很多这样的操作。Include JavaScript for effects inside old and new
content
block and rerun effect scripts after inserting new node with something like this:Also it can be good idea to delete old scripts from
head
somehow if you plan a lot of such operations.