开发者

ajax returning php/javascript code

开发者 https://www.devze.com 2023-01-18 04:36 出处:网络
I was playing around with AJAX. If I do echo \"helllo\" in the PHP file it works fine. However, if I do something like

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 any开发者_开发百科thing 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);
0

精彩评论

暂无评论...
验证码 换一张
取 消