executing javascript in PHP through echo, via ajax
so i build a login user system that has int eh html page a div container and a javascript file. in the javascript file, it makes ajax calls to different php pages that then echo back the html code for the form selected that is then inserted into the div container.
(Thus the page does not refresh - its dynamic content. and if someone grabs the source, all they get is the js file and a div container)
my problem nw is i need to run some javascript in the echo'd html in the php that is being called via ajax.
so ajax call to php, php echos a string and the ajax then performs a document.getElementById("Container").innerHTML=xmlhttp.responseText;
The php code i have has a 2 input fields, and i need it to element .focus ont he first one. so i have something like this being echod'd:
echo "
<form>
<input name='username' type='text' id='username'>
</form>
<script type='text/javascript'>
document.getElementById('username').focus();
</script开发者_如何转开发>
";
And guess what, it does not work.. Please help
(Thus the page does not refresh - its dynamic content. and if someone grabs the source, all they get is the js file and a div container)
They can still easily get the full source, by using firebug (firefox add-on) or some other tool. You can't protect your source code this way.
Idea #1: Use DOM to get the AJAX response, then append the new javascript to the head of the document.
Idea #2: Use a js framework to get the response, much easier. I know jQuery executes the script in AJAX response (getScript function, link). Here is a question with answers to do the same with Prototype framework.
Idea #3: Use eval(). This is not considered good practice though:
eval(document.getElementById('username').focus());
php is not problem here, nor in html nor in script. It works
http://sandbox.phpcode.eu/g/a571a.php
Use jQuery, it's very powerfull and easy js-library. You can do it in the success callback function like:
$.ajax({
url:'your_request_url_here',
dataType: 'html',
success:function(html){
$("#Container").html(html);
$("#username").focus();
}
});
It will be better if you will call the ajax request in the $(document).ready()
Why don't you take the script out of the response and put it in your receiver code?
document.getElementById("Container").innerHTML = xmlhttp.responseText;
document.getElementById('username').focus();
精彩评论