how do you get javascript code from the responseText?
How to pass javascript code into responseText? for example using this php:
开发者_如何学JAVA
<?php
echo "<script language='javascript'>
for(i=0;i<3;i++){
document.write(i);
}
</script>
";
?>
// output: 012
//and if you pass the php above into this responseText
document.getElementById('someId').innerHTML = xmlHTTPobj.responseText;
// there is no output
This code has been tested without ajax (php only), and it prints as expected, but not if you pass this php into responseText.
PS: there is no typo, there's no syntax error, the browsers are: ff4 + firebug 1.7, IE8, chrome 10, opera 10, and I just want to know how to pass javascript code into responseText?
edit:
PPS : Feel free to answer the question. Or does this mean you cannot pass javascript code into responseText?
This comes untested and straight for my (possibly deficient) memory, but I think you'll need to eval() any javascript for it to be executed like this. Then you'd just send back javascript without the script tags. As far as I remember (this is usually handled by frameworks), this is exactly how we send data structures back from the server to the client, using JSON
I had this problem in my app too. I'm not exactly sure how I solved it, but I had to alter my JS library (a very old Mootools). (It starts on line 3215 on http://hotblocks.nl/js/mootools_1_11.js.)
Some browsers execute the javascript when it's inserted into the DOM, some execute it when it's received (Ajax call completed) and some browsers don't ever. So the Mootools solution is to regex for <script>
blocks, separately eval the contents, replace the <script>
blocks (keep em, but empty) and then execute the complete handler.
I'll try to set up a little test to illustrate this.
edit
I found this example jsfiddle: http://jsfiddle.net/zalun/NF2jz/
It uses Mootools' Request.HTML: http://jsfiddle.net/js/lib/mootools-1.2.5-core-json-fixed.js
This part does what I said above:
success: function(text){
var options = this.options, response = this.response;
response.html = text.stripScripts(function(script){
response.javascript = script;
});
...
精彩评论