JavaScript innerHTML包括php

时间:2015-04-04 07:11:03

标签: javascript php html innerhtml

为什么我的代码不起作用?

function _(x){
    return document.getElementById(x);
}

function friends(){
    _("right").innerHTML = '<?php include_once "friendlist.php";?>';
}

结果:

<!--?php include_once "friendlist.php";?-->

我该如何解决?

6 个答案:

答案 0 :(得分:4)

你必须这样做

$(document).ready(function(){
  $("#your_id").click(function(){
    $("#your_div").load('friendlist.php');
  });
});

答案 1 :(得分:3)

使用以下代码可以使用

 <div id="right">
   <script>
      document.write('<?php echo include_once "include.php";?>');
   </script>
</div>

或者我测试下面的代码也会起作用

 <body>
     <div id ="right" >

     </div>
  </body>

  <script>
    function friends(){
     var x=document.getElementById("right");
     x.innerHTML = '<?php include_once "include.php";?>';
     }      
    friends();    
 </script>

答案 2 :(得分:0)

<script>   
 $(document).ready(function(){
      $("#id").click(function(){
        $("#div").load('friendlist.php');
      });
    });
</script>

尝试这样......

答案 3 :(得分:0)

这是不可能的,因为php在服务器上运行而不是在浏览器中运行。 使用方法:

  

$(“div”)。load(“php_file_name”)

答案 4 :(得分:0)

如果您的代码可以正常运行,则会严重违反安全规定。好东西是你不能通过你的浏览器注入和执行PHP代码:)你可以将php标签放在html文件中,你可以显示它,但它甚至不会通过服务器,更不用说执行它了。

另一方面,您可以在server上创建friendlist.php,并确保:

比在browser/client

中执行html / js
_("right").innerHTML = ajax('http://yout_site.com/friendlist.php');

顺便说一下,如果您使用JavaScript从服务器请求某些内容然后在浏览器中显示它,则称为ajax;)

只是为了好玩,你也可以使用http://www.upiur_site.com/friendlist.php'&gt;避免ajax。但这有许多缺点。 对于ajax函数使用库,编写自己的...

编辑:

如果服务器设置为解析.js文件,我错过了第三个选项。在那种情况下会起作用。

答案 5 :(得分:0)

我知道这是被询问和回答的,而且它与静态内容有关,但是值得指出的是,这些答案(非ajax)要求刷新整个页面以更新php内容。这是因为php include由服务器编译,然后发送到浏览器,在该浏览器中,javascript现在仅具有编译结果。

阅读此内容的用户可能希望创建动态内容,在这种情况下,更好的解决方案可能是让javascript获取页面。这可以通过以下方式实现。

<script type="text/javascript"> 
function updatePrices() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML = this.responseText;
    }
  };        
  xhttp.open("GET", "http://example.com/current_prices.php", true);
  xhttp.send();
}  
</script>

<div id="demo">
    <h2>Change This</h2>  
</div>
<button type="button" onclick="updatePrices();">Click Here!</button> 

ref:
    https://www.experts-exchange.com/questions/29091951/Include-php-file-with-JS.html     https://www.w3schools.com/xml/xml_http.asp

如果需要在计时器上刷新内容,也可以使用javascript setTimeout()函数。

请随时改进我的答案或将其添加到其他类似的问题中。