Is it Possible to execute a Javascript using AJAX call or calling a specific function in the Javascript.
I am able to display the contents of the Javascript file like "http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first " but not able to execute the javascript.
Is there any way. Actually I am a newbie AJAX
2 Answers 2
Ajax lets you do two things:
- Make a request to the server
- Read the response you get back
Anything else happens around that.
If you are, for instance, running NodeJS on the server, then the HTTP request will trigger some server side JavaScript.
If you get JavaScript back from the server, then you'll have that available in a string and you can do whatever you like to it (including passing it through eval()).
Generally speaking, fetching new JS from the server like that is a bad idea. Better to have your JavaScript loaded into your webpage up front and then just trigger it based on data you get back from the server.
3 Comments
Function constructor to read your code as well.eval (like new Function) are not really safer than eval :)If I am understanding correctly the case here is that the server is returning some javascript code and you like to evaluate it.
You can use the eval() function as described here.
In the example you provided it would be something like:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
eval(xhttp.responseText);
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
But you should be careful, because using eval is not always a good idea.
See this SO question: Why is eval a bad idea?
jquery.getScriptdoes? See this stackoverflow question.textContentproperty to the script you just receive, or use the reviledeval(not advised but it does work)...