the reponseText
should be like this on PHP
echo "<script>alert('test')</script>";
But nothing happen. How do I return Javascript code?
the reponseText
should be like this on PHP
echo "<script>alert('test')</script>";
But nothing happen. How do I return Javascript code?
An ajax call is up to the caller to decide what to do with it (depending upon what type of data is returned). In this case, if your caller isn't prepared to execute this, then nothing will happen with it. Depending upon what the real code wants to do here, there are a number of different possibilities for handling the returned result from the ajax call.
It could be formatted as JSONP so it calls a function in your main page code to process the returned data. You could return full JS (without the tags) and do an eval() on it after the host page (generally not considered a wise idea due to some security risks) or it could be just added to the current page and let the browser just parse whatever you put in there.
Usually, an Ajax call returns pure data and your host page code processes that data and holds the code for deciding what to do with it. This is the safest mechanism because there's no way for anything that hijaacked a connection to inject code into your page (all it can do is change the data).You've returned it as text. Now all you need to do is insert that text onto the page somehow:
document.body.innerHTML += response;
There's a lot going on, and a lot of assumptions made, but that's the simplest way to do it.
(Well, that's not entirely true. The easiest way to do it would be to just return the JavaScript, and then eval
it.)
here's a simple example. But don't include the <script>
tags for this tough
$.ajax({
type: "GET",
dataType: "text",
url: "jsLoader.php",
success: function(data){
eval(data);
}
});