[英]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.