【问题标题】:Change innerHTML from an external php file从外部 php 文件更改 innerHTML
【发布时间】:2013-05-08 05:40:07
【问题描述】:

我在 HTML 文件中有一个脚本,它每 30 秒运行一次 php 文件。 php 文件旨在更改 div 的 innerHTML。好像没找到替换的方法。

我使用的是load(),但有几个divs 我想每30 秒更新一次,我不想让服务器获取那么多请求。所以我只找一个php 获取然后更改这几个div中的innerhtml

这就是我所拥有的:

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
 ?>';

我认为问题是我无法从父 HTML 文件中获取元素。我不知道如何解决这个... 任何建议都将不胜感激!

【问题讨论】:

    标签: php javascript jquery innerhtml getelementbyid


    【解决方案1】:

    你正在重塑 jQuery 的 load()

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

    服务器应该只返回您想要显示的 HTML 内容。


    编辑

    由于您的评论与原始问题不同。

    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);
    

    您可能想要添加一个 onError 处理程序,并且可能想要为 Ajax 调用设置无缓存选项。

    【讨论】:

    • 有点...我使用的是load(),但有几个divs 我想每30秒更新一次,我不想让服务器获取那么多请求。所以我只寻找一个php 获取然后更改这几个div中的innerhtml
    • 如果从一开始就在您的信息中会有所帮助!
    【解决方案2】:

    你可能想要的是让你的 php.php 返回一些数据,然后你使用 $.get 的成功来更新你的#foo;从http://api.jquery.com/jQuery.get/ 中举一个例子并为你的例子修改它

    $.get("php.php", function( data ) {
        $( '#foo' ).html( data );
    });
    

    希望有帮助:)

    【讨论】:

    • 我不太明白你在说什么...我知道编码。我正在尝试在 div document.getElementById("foo").innerHTML = '&lt;? $line1= file_get_contents('example/foo.txt'); print htmlentities($line1);?&gt;'; 中打印以下内容
    • 不知道如何导出数据$line1在函数中使用
    • 我更新了问题,提供了有关我的问题的更多信息。也许现在你可以帮助我? ;)
    • 抱歉没回复,刚回复不久就下线了,不好意思。
    • 没问题。还是谢谢!!
    猜你喜欢
    • 1970-01-01
    • 2013-09-25
    • 2016-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-29
    • 2011-02-16
    • 1970-01-01
    相关资源
    最近更新 更多