[英]Need a javascript function in return of Ajax Call
我正在尝试在ajax调用中获取javascript函数。 我的代码运行正常,并返回了我的JavaScript代码,但是我收到的javascript函数有问题。 这是我的Ajax代码。
function media_type(id)
{
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
eval(document.getElementById("asad").innerHTML=xmlhttp.responseText);
}
}
xmlhttp.open("GET","video/media_type.php?cat_id="+id,true);
xmlhttp.send();
}
她是我返回一个简单的hello world警报框的代码。
if($num_rows==0)
{
//echo("Sorry no record found.");
echo'<script type="text/javascript">
alert("hello World");
</script>';
}
我正好收到代码,但是代码没有执行。 请告诉我如何解决此问题。 提前致谢。
请问为什么需要从服务器返回JavaScript? 您如何从服务器返回一个简单的响应(字符串,布尔值,数字),然后根据返回值执行已经存在于客户端的操作? 更安全,更轻松。 它可能不是您要寻找的解决方案,但是您的js-fu会更强大。
前几天我遇到了这个问题...
您必须将php页面中的标头设置为Content-Type:text / javascript; 字符集= utf-8
这是使此工作有效的整个代码
为您的PHP文件
<?php
header("Content-Type: text/javascript; charset=utf-8");
echo'<script type="text/javascript">
alert("hello World");
</script>
';?>
这是Javascript
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" type="text/javascript"></script>
<script>
$.ajax({
type:'POST',
url:'toget.php',
success:function(d)
{
$(document).append(d);
}
});
</script>
我会尝试这个
if($num_rows==0)
{
//echo("Sorry no record found.");
echo'<html><script type="text/javascript">
alert("hello World");
</script>
</html>';
}
我认为这条线造成了问题
eval(document.getElementById("asad").innerHTML=xmlhttp.responseText)
那是
eval(document.getElementById("asad").innerHTML='<script>alert("Hi");</script>';)
转换为
eval(document.getElementById("asad").innerHTML='< script > alert("Hi");</script>';)
只需返回要执行的JS( alert("hello World");
)并进行eval
。 删除<script type="text/javascript">
和</script>
eval(xmlhttp.responseText);
将会:
eval('alert("hello World")');
//try using this
<?php
if($num_rows==0)
{
//echo("Sorry no record found.");
?>
<script type="text/javascript">
alert("hello World");
</script>
<?php
}
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.