开发者

Echoing <script> from PHP to jQuery AJAX causes problems with my interval

Basically, I'm grabbing contents from a PHP file. I check it every 5 seconds. If the content differs from the content on the page, it loads that new content:

    <script type="text/javascript">
    $(document).ready(function()
    {
        $.ajaxSetup ({ cache: false });  

        var loadUrl = "<?php echo site_url("admin/get_uploads"); ?>";  

        $("#result").load(loadUrl);

        var refreshId = setInterval(function() {
            $.get(loadUrl,function(result){
                if(result !=  $("#result").html())
                {
                    $("#result").html(result);
                    $("#result").effect("highlight", {}, 2000);
                }
            });
        }, 2000);
    });  
    </script>

My PHP is as follows:

    function get_uploads()
    {
        $this->db->order_by('upload_date', 'desc');
        $uploads = $this->je_model->get_uploads(array('new' => TRUE));

        echo '<script>function delete_upload(id){$.ajax({type: "POST",url: "'.site_url("admin/delete_upload").'/" + id,success: function(html){$("#" + id).hide();}});}</script>';

        if ($uploads == NULL):
            echo 'NO NEW UPLOADS';
        else:
            foreach ($uploads as $row):
                echo '<p id="'.$row->id.'">'.$row->file.' '.anchor('admin/file/'.$row->id.'/complete', 'Complete', 'title="Complet开发者_开发百科e"').' '.anchor('#', 'Delete', 'title="Delete File" onclick="delete_upload('.$row->id.'); return false"').'</p>';
            endforeach;
        endif;
    }

I'm echo'ing the tag. With the script tag in there, my #result DIV constantly re-loads. For some reason, the Javascript is thinking there's a difference between the content when there shouldn't be. When I remove the tag from my PHP, it works as it should. It only updates if there are new uploads.

Any ideas what's wrong here?


Change your function to return json, and do your processing in javascript.


You might have luck if you set the headers and type:

header('Content-type: text/javascript');
echo "<script type=\"text/javascript\">" ...

Byron's suggestion to use JSON is probably the ideal solution though

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜