如何在php代码中调用javaScript函数

如何在php代码中调用javaScript函数,javascript,php,html,Javascript,Php,Html,我想在php Div中调用javaScript函数。我尝试了一些方法,但都不起作用。 下面是代码行 <!DOCTYPE html> <html> <head> <title>Title</title> </head> <body> <div class="container"> //Set the image here. (I would like to set the image here

我想在php Div中调用javaScript函数。我尝试了一些方法,但都不起作用。 下面是代码行

<!DOCTYPE html>
<html>
<head>
<title>Title</title>
</head>
<body>

<div class="container">
    //Set the image here. (I would like to set the image here. )
    //That is what I have tried, but it does not work.
    <?php $img_name = echo  $row['img_name']; ?> //e.g. $img_name = cat.jpg; ?>
    //Call the  img() function to set the image
    echo '<script type="text/javascript">', 'img('.$img_name.');', '</script>';
</div>

标题
//在这里设置图像。(我想在这里设置图像。)
//这是我尝试过的,但它不起作用。
//e、 g.$img_name=cat.jpg;?>
//调用img()函数来设置图像
回显“”,“img('.$img_name.);”,“”;
下面是js函数

<script>
function img(img_src){
    //Create div
    var m_div = document.createElement('Div');
    m_div.style.background = "green";
    m_div.id = "id_div";

    //Create img
    var img_input = document.createElement('img');
    img_input.id = "id_img"; 
    img_input.src = "images/" + img_src; // e.g. img_src = cat.jpg;
    img_input.height = "380";
    img_input.width = "290";

    //Append img to div
    document.getElementById("m_div").appendChild("img_input");
}
</script>

函数img(img_src){
//创建div
var m_div=document.createElement('div');
m_div.style.background=“绿色”;
m_div.id=“id_div”;
//创建img
var img_input=document.createElement('img');
img_input.id=“id_img”;
img_input.src=“images/”+img_src;//例如,img_src=cat.jpg;
img_input.height=“380”;
img_input.width=“290”;
//将img附加到div
document.getElementById(“m_div”).appendChild(“img_输入”);
}
先谢谢你


您不能从PHP调用javascript。您必须使用PHP生成HTML,而HTML又可以调用javascript函数。将PHP变量->中的图像文件名打印到HTML->中,作为javascript函数的参数值

    $img_name = 'showMe.jpg';
    echo '<script type="text/javascript">img("'.$img_name.'")</script>';
$img_name='showMe.jpg';
回显“img”(“$img_name.”);

您不能从PHP调用js。PHP是一种后端语言,表示在加载javascript之前运行,javascript是一种前端语言,表示在浏览器加载页面之后加载

但是,您可以将PHP传递给javascript,但不建议这样做。最好使用从服务器加载变量。这是一个链接,可以阅读有关的更多信息

例如:

//Call the  img() function to set the image
<script type="text/javascript">
  var row = <?php echo  json_encode($row); ?>; //e.g. $img_name = cat.jpg; ?>
  (function(image) {
      img(image);
  })(row.img_name);
</script>
//调用img()函数设置图像
var行=//e、 g.$img_name=cat.jpg;?>
(功能(图像){
img(图像);
})(第行,img_名称);

将任意数据注入脚本(甚至HTML)不是一个好主意。至少使用
json\u encode()
兼容。谢谢@user\u pt。我已经考虑了你的意见,并且提出了另一个问题,请看一下。谢谢@Fermin Perdomo。我已经考虑了你的意见,我又提出了一个问题,请看一下。