douchen7324 2013-05-14 03:42
浏览 64
已采纳

从外部php文件更改innerHTML

I've got a script in an HTML file that runs a php file every 30 seconds. The php file is intended to change a div's innerHTML. I don't seem to find the way to replace it.

I was using load() but there are several divs I want to keep updating every 30 seconds and I don't want to make the server GET that much requests. So I'm looking for one only php get and then change the innerhtml in those several divs

This is what i've got:

HTML:

<script type="text/javascript">
$(document).ready(function () {
    $.get('php.php');
});
setInterval(function(){
    $.get('php.php');
}, 30000);
</script>

<div id="foo"></div>

php.php:

document.getElementById("foo").innerHTML = '<?php
// some php code
 ?>';

I think the problem is I'm not being able to get the element from the parent HTML file. I don't know how to solve this... Any suggestions will be more than aprecciated!

  • 写回答

2条回答 默认 最新

  • dougeqiang1619 2013-05-14 04:04
    关注

    You are reinventing jQuery's load()

    function fetchContent() {
         $("#foo").load('php.php');
         window.setTimeout(fetchContent, 30000);
    }
    $(fetchContent);
    

    The server should just return the HTML content that you want to display.


    EDIT

    Since your comment is different from the original question.

    function fetchContent() {
         $("#foo").get('php.php', function(data) {
             var html = $("<div/>").html(data);             
             $("#foo").html( html.find("#Section1").html() );
             $("#bar").html( html.find("#Section2").html() );
             $("#asd").html( html.find("#Section3").html() );
             window.setTimeout(fetchContent, 30000);
         });
    }
    $(fetchContent);
    

    You would want to add an onError handler and might want to set the no cache option for the Ajax calls.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作