javascript 在ajax加载页面后执行javascript脚本 - 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10888326/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Executing javascript script after ajax-loaded a page - doesn't work
提问by Deukalion
I'm trying to get a page with AJAX, but when I get that page and it includes Javascript code - it doesn't execute it.
我正在尝试使用 AJAX 获取页面,但是当我获取该页面并且它包含 Javascript 代码时 - 它不会执行它。
Why?
为什么?
Simple code in my ajax page:
我的ajax页面中的简单代码:
<script type="text/javascript">
alert("Hello");
</script>
...and it doesn't execute it. I'm trying to use Google Maps API and add markers with AJAX, so whenever I add one I execute a AJAX page that gets the new marker, stores it in a database and should add the marker "dynamically" to the map.
...它不执行它。我正在尝试使用 Google Maps API 并使用 AJAX 添加标记,因此每当我添加一个标记时,我都会执行一个 AJAX 页面来获取新标记,将其存储在数据库中,并且应该“动态”地将标记添加到地图中。
But since I can't execute a single javascript function this way, what do I do?
但是由于我无法以这种方式执行单个 javascript 函数,我该怎么办?
Is my functions that I've defined on the page beforehand protected or private?
我事先在页面上定义的函数是受保护的还是私有的?
** UPDATED WITH AJAX FUNCTION **
** 使用 AJAX 功能更新 **
function ajaxExecute(id, link, query)
{
if (query != null)
{
query = query.replace("amp;", "");
}
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
if (id != null)
{
document.getElementById(id).innerHTML=xmlhttp.responseText;
}
}
}
if (query == null)
{
xmlhttp.open("GET",link,true);
}
else
{
if (query.substr(0, 1) != "?")
{
xmlhttp.open("GET",link+"?"+query,true);
}
else
{
xmlhttp.open("GET",link+query,true);
}
}
xmlhttp.send();
}
** Solution by Deukalion **
** Deukalion 的解决方案 **
var content = xmlhttp.responseText;
if (id != null)
{
document.getElementById(id).innerHTML=content;
var script = content.match("<script[^>]*>[^<]*</script>");
if (script != null)
{
script = script.toString().replace('<script type="text/javascript">', '');
script = script.replace('</script>', '');
eval(script);
}
}
and on certain events, I had to within the script addevent listeners instead of just making a "select onchange='executeFunctionNotIncludedInAjaxFile();'" I had to addEventListener("change", functionName, false) for this. In the script that is being evaluated.
对于某些事件,我必须在脚本中添加事件侦听器,而不是仅仅创建一个“select onchange='executeFunctionNotIncludedInAjaxFile();'”,为此我不得不 addEventListener("change", functionName, false)。在正在评估的脚本中。
回答by Pointy
When you update your page by doing something like setting a container's innerHTML
to some updated content, the browser simply will not run the scripts in it. You can locate the <script>
tags, get their innerHTML
(IE may prefer innerTEXT
), and then eval()
the scripts yourself (which is pretty much what jQuery does, though it finds the scripts with a regex before updating the DOM).
当您通过执行诸如将容器设置innerHTML
为某些更新内容之类的操作来更新页面时,浏览器根本不会运行其中的脚本。您可以找到<script>
标签,获取它们innerHTML
(IE 可能更喜欢innerTEXT
),然后eval()
是自己的脚本(这几乎是 jQuery 所做的,尽管它在更新 DOM 之前使用正则表达式查找脚本)。
回答by Jake
Use this function:
使用这个功能:
function parseScript(_source) {
var source = _source;
var scripts = new Array();
// Strip out tags
while(source.indexOf("<script") > -1 || source.indexOf("</script") > -1) {
var s = source.indexOf("<script");
var s_e = source.indexOf(">", s);
var e = source.indexOf("</script", s);
var e_e = source.indexOf(">", e);
// Add to scripts array
scripts.push(source.substring(s_e+1, e));
// Strip from source
source = source.substring(0, s) + source.substring(e_e+1);
}
// Loop through every script collected and eval it
for(var i=0; i<scripts.length; i++) {
try {
eval(scripts[i]);
}
catch(ex) {
// do what you want here when a script fails
}
}
// Return the cleaned source
return source;
}
then do parseScript(xmlhttp.responseText);
when you're replacing/adding content.
然后parseScript(xmlhttp.responseText);
在替换/添加内容时执行。
回答by Jason Chapman
In case some other people stumble upon this old thread, there is one issue with the accepted answer by Deukalion, there is one issue that may have been overlooked: as written, the script only looks for the firstscript tag. If multiple script tags exist, all others are overlooked.
万一其他人偶然发现了这个旧线程,Deukalion 接受的答案存在一个问题,有一个问题可能被忽略了:正如所写,脚本只查找第一个脚本标签。如果存在多个脚本标记,则会忽略所有其他脚本标记。
A few minor tweaks would resolve the issue. Change one line from:
一些小的调整将解决这个问题。更改一行:
var script = content.match("<script[^>]*>[^<]*</script>");
To:
到:
var script = content.match(/<script[^>]*>[^<]*<\/script>/g);
And another from:
另一个来自:
script = script.toString().replace('<script type="text/javascript">', '');
To:
到:
script = script.join("").replace(/<script type="text\/javascript">/g, '');
Now it will gather all the <script> code and execute them in the order found on the page. Otherwise it was an excellent solution.
现在它将收集所有 <script> 代码并按照页面上的顺序执行它们。否则,这是一个很好的解决方案。
回答by Alexander Bird
After the AJAX request, you can make an "on success" function which can take the returned html and do something with it. Thensomething will be executed.
在 AJAX 请求之后,您可以创建一个“成功”函数,该函数可以获取返回的 html 并对其进行处理。然后将执行某些操作。
If there was a code example, then I could provide a code solution to the situation. But using just standard xmlhttprequest, the following could be done:
如果有代码示例,那么我可以针对这种情况提供代码解决方案。但是只使用标准的 xmlhttprequest,可以做到以下几点:
xhr = new XMLHttpRequest();
xhr.open("GET","ajax_info.txt",true);
xhr.onreadystatechange=function()
{
if (xhr.readyState==4 && xhr.status==200)
{
document.getElementById("myDiv").innerHTML = xhr.responseText;
}
}
xhr.send();
?