简体   繁体   中英

ajax returning php/javascript code

I was playing around with AJAX.

If I do

echo "helllo"

in the PHP file it works fine.

However, if I do something like

echo "<script language=Javascript> alert('hi');</script>";

in the PHP file, the alert() does not come up.

Anyone know if I'm doing anything wrong?

example:

in my html file i've got this

<div id='something'> </div>

and i want the response text from the php file be placed above:

if (req.status==200) {
     document.getElementById('something').innerHTML=req.responseText;
}

if i changed that to:

if (req.status==200) {
     document.getElementById('something').innerHTML="<?php echo 'hi';?>";
}

it works fine, the response text will be ---> hi
but if i do echo "\\"<?php echo 'hi';?>\\""; in my php file, the response text will be ""

i hope i was clear in explaining

use $.load() , and the script will be evaluated.

$("#something").load("request.php");

Maybe jQuery there also uses eval() , so it is'nt more safe, but as long as load() only works on the same Domain u should have Control over the things that will be evaluated.

However, it is easier to use, because you did'nt have to parse the Fragment for script's on your own :)

another approach: using eval

var result = ajaxResponseText;// "alert('hi')"; in your case
eval(result);

You must create script tag with returned data;

var script = document.createElement('script');
stript.innerHTML = req.responseText;
document.getElementsByTagName('head')[0].appendChild(script);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM