douchen7324
2013-05-14 03:42
浏览 63

从外部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.

    已采纳该答案
    打赏 评论
  • dongshi6844 2013-05-14 03:49

    what you probably want is for your php.php to return some data, and then you use the success of the $.get to update your #foo; taking an example from http://api.jquery.com/jQuery.get/ and modifying it for your example

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

    hope that helps :)

    打赏 评论

相关推荐 更多相似问题