Execute JavaScript within responseHTML
When using responseHTML with XHR, Firefox executes the javascrip开发者_StackOverflow社区ts within the loaded responseHTML, chromium does not. if i add a script that will parse and execute the scripts, it will work on chromium but they result being executed twice in Firefox. Any idea how to know if browser will execute loaded scripts or not other than through agent sniffing? PS: I'm using a JS framework that IS NOT jQuery or Prototype or anything
This is the n'th time I've answered this question now :)
// response is the data returned from the server
var response = "html\<script type=\"text/javascript\">alert(\"foo\");<\/script>html";
var reScript = /\<script.*?>(.*)<\/script>/mg;
response = response.replace(reScript, function(m,m1) {
eval(m1); //will run alert("foo");
return "";
});
alert(response); // will alert "htmlhtml"
Don't sniff. Test. I don't remember the mechanics of exactly when Mozilla fires the scripts, but it should be possible to manufacture an internal test that detects if scripts are fired and then to patch accordingly.
Don't use responseHTML. Use responseText instead and use the following function. The onSuccess function is important to you. Use it in your success handler of ajax request.
function showHtmlInElement(targetId, htmlUrl) {
var target = document.getElementById(targetId);
var Util = jaf.core.Util;
Util.ajax({
url: htmlUrl,
dataType: "text/html",
// ---------------------------------------------------------------
onSuccess: function(xhr) {
var responseText = xhr.responseText;
target.innerHTML = responseText;
// collect all the script tag content...
var scriptText = "";
var arrScripts = target.getElementsByTagName("script");
for(var i = 0, len = arrScripts.length; i < len; i++) {
var se = arrScripts[i];
scriptText += se.innerHTML;
}
if((scriptText = Util.trim(scriptText)).length != 0) {
eval.call(window, scriptText);
}
},
// ---------------------------------------------------------------
onError: function(xhr, code, message) {
var responseText = xhr.responseText;
var content = "<p class='error'>" + responseText + ": "
+ message + "(" + code + ")</p>";
target.innerHTML = content;
}
});
}
I've tested this opera, firefox, chromium, safari. Haven't tested in IE6 though.
精彩评论