Δευτέρα 4 Οκτωβρίου 2010

How to run JavaScript after sucessful completion of Ajax request

A common issue that rises whenever you make ajax call is how you 'll be able to call initializing javascript of the changed html elements. A potential solution is to create a javascript function that you 'll call after the success complete of the ajax request.
There is also another solution that is even better and more dynamic. This solution is to use a method that parses your whole html and call any part of scripting code.

The code [1]:
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
try {
if((scripts[i]).indexOf("parseScript(")==-1){//ignore javascript of current function!!
eval(scripts[i]);
}
}
catch(ex) {
alert(scripts[i]);
alert(ex);
// do what you want here when a script fails
}
}
// Return the cleaned source
return source;
}

Additional notes:
I propose you to use jquery and add any code that should be called in functions that had window load event:
$(window).load(function(){//whatever you want to execute});
And after successful completion of ajax request to trigger the load event of window by calling
$(window).trigger("load");

References:
[1] Evaluate scripts while working on AJAX Requests [http://www.developersnippets.com/2009/05/20/evaluate-scripts-while-working-on-ajax-requests/]
[2] Run Javascript Code After an AJAX Request [http://www.linein.org/blog/2009/06/05/run-javascript-code-after-an-ajax-request/]


Δεν υπάρχουν σχόλια:

LinkWithin

Blog Widget by LinkWithin

Mobile edition